Search code examples
phplaravellaravel-5.6laravel-testing

How to Set Up a Test for the Destroy Method Laravel 5.6


I'm going through the testing on my app, and I've gotten to the point where I need to test the destroy method of my controller. The test as I have it currently is:

public function test_user_can_delete_draft()
{
  $user = factory(User::class)->states('confirmed', 'normaluser')->create();
  $userForm = factory(Form::class)->states('in_house_signs')->create(['user_id' => $user->id, 'status' => 'draft',]);
  // Test creator can delete form
  $response = $this->actingAs($user)->delete(route('forms.destroy', $userForm));
  $response->assertSuccessful();
}

And the method in the controller that I am testing is:

public function destroy($id) {
   $form = Form::find($id);
   Comment::where('form_id', $id)->delete();
   $form->delete();

   // Redirect
   return redirect()->back()->with('status', 'Form successfully deleted');
}

When I run phpunit, I get the error:

Response status code [302] is not a successful status code.
Failed asserting that false is true.

What should I do to get the test to run properly?


Solution

  • you could try to use assertRedirect https://laravel.com/docs/5.6/http-tests#assert-redirect

    or use the status check:

    $response->assertStatus(302) https://laravel.com/docs/5.6/http-tests#assert-status

    or if you really want to check if the record is being deleted you could check the database in your test if the record is deleted $this->assertEquals(Comment::where('form_id', $userForm->id)->first(),null)