Introduction
Laravel provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the assertDatabaseHas helper to assert that data exists in the database matching a given set of criteria. For example, if you would like to verify that there is a record in the users table with the email value of sally@example.com, you can do the following:
public function testDatabase() { // Make call to application... $this->assertDatabaseHas('users', [ 'email' => 'sally@example.com' ]); }
You can also use the assertDatabaseMissing helper to assert that data does not exist in the database.
Of course, the assertDatabaseHas method and other helpers like it are for convenience. You are free to use any of PHPUnit’s built-in assertion methods to supplement your tests.
Generating Factories
To create a factory, use the make:factory Artisan command:
php artisan make:factory PostFactory
The new factory will be placed in your database/factories directory.
The –model option may be used to indicate the name of the model created by the factory. This option will pre-fill the generated factory file with the given model:
php artisan make:factory PostFactory –model=Post
Resetting The Database After Each Test
It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests. The RefreshDatabase trait takes the most optimal approach to migrating your test database depending on if you are using an in-memory database or a traditional database. Use the trait on your test class and everything will be handled for you: