A short lesson mentioning the assertion helpers related to Eloquent models.
Instead of a typical assertDatabaseHas()
to check the database for specific tables and fields, if you are checking the Eloquent model, you may use the entire model and a assertModelExists()
. Then, you won't need to specify the table and the fields. You will only provide the Eloquent model.
Laravel is smart enough to guess the table from that Eloquent model and check if the entire Model object exists in the database.
In this test, two assertions perform the same operation. You can choose which method to use.
use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); test('update product contains correct values', function () { $product = Product::factory()->create(); $this->assertModelExists($product); $this->assertDatabaseHas('products', [ 'name' => $product->name, 'price' => $product->price, ]); });
Similarly, a method to check if the model doesn't exist in the database is called assertDatabaseMissing()
.
In this test, instead of using assertDatabaseMissing()
and providing the table name with fields and values, you can use the assertModelMissing()
helper and provide only the Eloquent model.
use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); test('products delete successful', function () { $product = Product::factory()->create(); actingAs($this->user) ->delete('/products/' . $product->id); $this->assertDatabaseMissing('products', $product->toArray()); $this->assertModelMissing($product);});
So, these are two helpers related to Eloquent models.