Assert if a Laravel model exists in your tests
April 25, 2022 ‐ 1 min read
Testing HTTP endpoints in your Laravel application works quite conveniently, there are enough tools available to quickly set up the code to test a response and its JSON structure for example.
Besides checking for response codes, in some cases I like to check for whether a model was actually persisted in the database. Often I like this added security check on authorized destroy endpoints.
Luckily there is a method for this as well that makes it easy to check whether a model does actually exist in the database; assertModelExists()
.
<?php
namespace Tests\Feature\Controllers\PageController;
use App\Models\Page;
use Tests\TestCase;
class PageControllerDestroyTest extends TestCase
{
public function test_authentication_required()
{
// Setup the models we need using test factories
$page = Page::factory()->create();
// Make the request
$response = $this->deleteJson(route('pages.destroy', [$page->id]));
// Make our assertions
$response->assertStatus(401);
$this->assertModelExists($page);
}
}
The assertModelExists()
test method makes use of the assertDatabaseHas()
method and just checks whether a model exists in the database with the same primary key.