PHPUnit Deleteとモデルのpath()の書き方

deleteのテストメソッドでは、deleteやdestroyではなくassertCountで確認するので注意が必要

### PHPUnit delete
/tests/Feature/BookReservationTest.php

public function test_a_book_can_be_deleted(){

        $this->withoutExceptionHandling();
        
        $this->post('/books', [
            'title' => 'Cool Title',
            'author' => 'Victor'
        ]);

        $book = Book::first();
        $this->assertCount(1, Book::all());

        $response = $this->delete('/books/'. $book->id);
        $this->assertCount(0, Book::all());
     $response->assertRedirect('/books');
    }

$ phpunit –filter test_a_book_can_be_deleted

route

Route::delete('/books/{book}', 'BooksController@destroy');

BooksController.php

public function destroy(Book $book){
    	$book->delete();
    	return redirect('/books');    	
    }

$ phpunit –filter test_a_book_can_be_deleted
OK (1 test, 2 assertions)

### modelによるpath()の関数化
Book.php

use Illuminate\Support\Str;
public function path(){
    	return '/books/' . $this->id . '-' . Str::slug($this->title);
    }

BooksController.php

return redirect($book->path());

BookReservationTest.php
// test methodも同様に使う

public function testa_book_can_be_added_to_the_library(){
        

        $this->withoutExceptionHandling();

        $response = $this->post('/books', [
            'title' => 'Cool book Title',
            'author' => 'victor',
        ]);

        $book = Book::first();

        $this->assertCount(1, Book::all());
        $response->assertRedirect($book->path());

    }

‘/${dirName}/’ . $this->id はよく使う書き方なので、modelにまとめるとすっきりする