Ray Lee | 李宗叡
Learn or Die
Published in
5 min readApr 5, 2021

--

Photo by benjamin lehman on Unsplash

# 版本

Laravel 8.x

# 前言

我喜歡使用 Laravel 開發的感覺, 除了開發快速, 程式碼簡潔且優雅之外, Laravel 框架本身也是一個很好的學習參照物。 本篇主要將官方文件重點整理成 Q&A 的形式呈現, 原子化的概念, 這方式並不適用於每個人, 但若對你有幫助, 我會很開心。

# 目錄

Laravel — 官方文件原子化翻譯 — 目錄

# Introduction

# Resetting The Database After Each Test

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
class ExampleTest extends TestCase
{
use RefreshDatabase;

public function test_basic_example()
{
$response = $this->get('/');

// ...
}
}
  • Answer: 使用 RefreshDatabase trait, 這樣每次 testing 之前都會 refresh database, 不讓之前的 test 影響到這次的 test

# Defining Model Factories

# Concept Overview

Model Factories 部分請參考 Seeding

# Running Seeders

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
public function test_orders_can_be_created()
{
$this->seed();

$this->seed(OrderStatusSeeder::class);

// ...
}
  • Answer: 在 testing 中可以直接使用 seed() 來執行定義好的 seeders

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
class ExampleTest extends TestCase
{
protected $seed = true;

// ...
}
  • Answer: 在 testing class 中定義 $seed property 為 true, 那每次 refresh database 時都會自動執行 db:seed

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
use Database\Seeders\OrderStatusSeeder;

protected $seeder = OrderStatusSeeder::class;
  • Answer: 當 testing class 中的 $seed property 設為 true 時, 每一次 refresh database 都會自動執行 db:seed, 可在 seeder property 定義要執行哪一個 seed class

# Available Assertions

# assertDatabaseCount

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
$this->assertDatabaseCount('users', 5);
  • Answer: assert users table 中有五筆資料

# assertDatabaseHas

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
$this->assertDatabaseHas('users', [
'email' => 'sally@example.com',
]);
  • Answer: assert users table 中有 email column 且 value 為 sally@example.com

# assertDatabaseMissing

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
$this->assertDatabaseMissing('users', [
'email' => 'sally@example.com',
]);
  • Answer: assert users table 中沒有 email column 且 value 為 sally@example.com 這筆資料

# assertDeleted

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
use App\Models\User;

$user = User::find(1);

$user->delete();

$this->assertDeleted($user);
  • Answer: assert 指定的 Eloquent model 已被刪除

以下的 Laravel Testing example code 的意思是?

  • Example:
<?php
$this->assertSoftDeleted($user);
  • Answer: assert 指定的 Eloquent model 已被 soft deleted

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.