LaravelでMutatorsにCarbonを使うときのPHPUnit testメソッドの書き方

carbonでset attributeを使うときは、modelでsetDobAttributeとし、testメソッドでは、$this->assertInstanceOf(Carbon::class, … と書く

## make:test
$ php artisan make:test AuthorManagementTest

テスト駆動開発でも、DBのリレーション関係に沿って開発するのは変わらない

use RefreshDatabase;

    public function test_an_author_can_be_created(){

        $this->withoutExceptionHandling();
        $this->post('/author', [
            'name' => 'Author Name',
            'dob' => '05/14/1988'
        ]);

        $this->assertCount(1, Author::all());
    }

$ phpunit –filter test_an_author_can_be_created

Route::post('/authors', 'AuthorsController@store');

$ php artisan make:controller AuthorsController
AuthorsController.php

public function store(){
    	Author::create(request()->only([
    		'name','dob'
    	]));
    }

$ php artisan make:model Author -m
Athor.php

class Author extends Model
{
    //
    protected $fillable = ['name', 'dob'];
}

migration file

Schema::create('authors', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamp('dob')
            $table->timestamps();
        });
use Carbon\Carbon;
use App\Author;
public function test_an_author_can_be_created(){

        $this->withoutExceptionHandling();
        $this->post('/author', [
            'name' => 'Author Name',
            'dob' => '05/14/1988'
        ]);
        $author = Author::call();

        $this->assertCount(1, $author);
        $this->assertInstanceOf(Carbon::class, $author->first()->dob);
    }

$ phpunit –filter test_an_author_can_be_created
Failed asserting that ’05/14/1988′ is an instance of class “Carbon\Carbon”.

Author.php

protected $dates = ['dob'];
public function setDobAttribute($dob){
    	$this->attributes['dob'] = Carbon::parse($dob);
    }
public function test_an_author_can_be_created(){

        $this->withoutExceptionHandling();
        $this->post('/authors', [
            'name' => 'Author Name',
            'dob' => '05/14/1988'
        ]);
        $author = Author::all();

        $this->assertCount(1, $author);
        $this->assertInstanceOf(Carbon::class, $author->first()->dob);
        $this->assertEquals('1988/14/05', $author->first()->dob->format('Y/d/m'));
    }

$ phpunit –filter test_an_author_can_be_created
OK (1 test, 3 assertions)

git add .
git commit -m “add author”

Test methodというより、mutatorsのcarbonの使い方の方が勉強になりました。