2tunnels's avatar

How to test firstOrFail?

I have a method on my controller:

public function show($slug)
{
    $category = Category::whereSlug($slug)->firstOrFail();
}

I want to write a simple test:

public function testCagegoryDoesNotExist()
{
    $this->visit('category/lorem')->assertResponseStatus(500);
}

But now I'm getting only exception and test fails. Should I mock Category model or there is another easy way to test that.

0 likes
4 replies
devinfd's avatar

This is something you probably don't need to test. firstOrFail is part of laravel and therefore it's up to laravel to ensure that it works.

2tunnels's avatar

My idea was to create such test: go there, ensure it fails, create category, go there again, ensure it succeed.

Or mby that's wrong. I just like to write false positive tests first. It shouldn't work just yet :)

kfirba's avatar

@2tunnels You need to tell PHPUnit that you are expecting an exception like so:

/** @expectedException  \Illuminate\Database\Eloquent\ModelNotFoundException  */
public function testCagegoryDoesNotExist()
{
    $this->visit('category/lorem');
}

Please or to participate in this conversation.