moxir's avatar
Level 1

HTTP Test

Hi, I'm trying to create tests for my application. However, when I try to test CRUD operations, the instance passed into the method is not loaded from the database. Let's say I have this method:

public function destroy(Comment $comment)
    {
        $comment->delete();
        return redirect()->back();
    }

Now, when using the application, everything is working. The comment is correctly loaded and then deleted. However, when I try to test it:

$user = factory(\App\Models\Users\User::class)->create();
        $comment = factory(Comment::class)->create();
        $response = $this->actingAs($user)->delete(route('comment.destroy', ['comment' => $comment]), [

        ]);

the destroy method is called, but the $comment variable is not the one from the db. In fact, it has zero attributes, and the attribute exists is false. If I do it like this:

public function destroy($id)
    {
	$comment = Comment::find($id);
        $comment->delete();
        return redirect()->back();
    }

it works. But why is the Eloquent Instance not loaded when calling the url from test, but it is when calling it from the application? Thank you in advance for your help.

0 likes
6 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Check Http/Kernel.php. It should have \Illuminate\Routing\Middleware\SubstituteBindings::class, in web and api middlewareGroups.

moxir's avatar
Level 1

Thank you very much, that was it, I had it disabled for testing env.

bugsysha's avatar

You are very welcome. Why would you do that?

moxir's avatar
Level 1

To disable CSFR validation on test request at first, but then I found a better way, but forgot to enable middlewares again in test case.

bugsysha's avatar

How does CSRF validation relate to this middleware? There is a separate middleware for CSRF token validation.

moxir's avatar
Level 1

I used the Withoutmiddleware trait, therefore all the middlewares were disabled

Please or to participate in this conversation.