bwrigley's avatar

Feature Test to replicated Delete method in Route Model Binding

Hello,

I'm trying to write feature tests around a new controller which uses the route model binding. But I'm having trouble replicating the DELETE method.

so my routes look like this:

Route::group(['middleware' => 'admin', 'prefix' => 'admin', 'as' => 'admin.'], function () {
   
    Route::get('/', 'AdminController@dashboard')->name('dashboard');
    Route::resource('administrator', 'AdminController');
});

and my test currently looks like this

        $deleteData = [
            '_method' => 'DELETE',
            'id' => $this->user->id
        ];

        $this->post('admin.administrator.destroy', $deleteData)
            ->assertViewIs('admin.index');

The error I get is:

1) Tests\Feature\AdminTest::testSelfDelete
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:

I presume it's something wrong in my $deleteData above? Thanks!

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

The URI will be incorrect for the delete action; you are posting to admin.administrator.destroy rather than to admin/administrator/123 (where 123 would be the $this->user->id.

The correct form for the URI is admin/administrator/123, which you can get using the route helper:

route('admin.administrator.destroy', $this->user->id)

Rather than making a test postrequest, you can make a delete request:

$this->delete(route('admin.administrator.destroy', $this->user->id))
            ->assertViewIs('admin.index');
1 like
bwrigley's avatar

Ah yes I see thank you. I thought there was no delete() helper.

However, running this now gives me a TokenMismatchException so presumably I need to include my token in the delete request also?

Please or to participate in this conversation.