You could intercept the ModelNotFoundException in the Handler and return a 404 JSON response from there.
Feature test findOrFail not giving 404 status
I am testing if a user enters a profile page that does not exists in the database. What is the best way to test these kind of errors. I was thinking that if I get a status of 404 it will make sense but I receive an exception.
Here is the test:
/** @test */
public function profile_url_must_be_valid_user_id()
{
$response = $this->get('/invalid-user-id');
$response->assertStatus(404);
}
Here is the route:
Route::get('/{user}', function($user) {
$user = User::firstOrFail($user);
return $user;
});
But as I said I receive this exception:
Illuminate\Database\Eloquent\ModelNotFoundException
which I can change my test to pass with the following:
/** @test */
public function profile_url_must_be_valid_user_id()
{
$this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException');
$response = $this->get('/invalid-user-id');
}
Is this the best way or I am doing it wrong? BTW, there is no issues in my manual testing (browser) As the page redirects automatically to my custom 404.blade.php page.
Not the only option, but probably the one I would reach for in the first instance; and you did mention wanting a 404 ;)
Once you catch the exception in the handler, you can do whatever you feel is appropriate, e.g. a redirect, return a view etc.
Please or to participate in this conversation.