Testing Models & the Database

Put use RefreshDatabase; in the test class. Laravel then runs migrate:fresh (deletes all the tables and creates them again) once, before the first test. It…

A test creates 3 users, then checks that the table users holds 3 rows. Suddenly that test fails: the table holds 4. You run it again, and the number becomes 8. The code hasn't changed at all. What changed is the table, because data from other tests and from the previous run (a run: running all the tests once) is still stored in it.

That's why a test that touches the database has to start from a state that is clean and predictable. Laravel gives you three tools for that: the RefreshDatabase trait (the database is cleaned for every test), factories (makers of sample data), and database assertions like assertDatabaseHas. A trait is a set of methods you can add to a class with use. Picture the counter of a shop, used by cashiers who work in shifts. Every cashier has to start from an empty counter and count only the money they receive. If the previous cashier left money on the counter, the next cashier's count is wrong, and nobody knows why. In this picture, each cashier is one test, the counter is the database, and the money left behind is data left over from other tests. RefreshDatabase empties the counter for every cashier.

One database test file

The file below holds three tests for the table users. User is a model: a Laravel class that stands for the table users, so one User object is one row.

<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_be_created(): void
    {
        User::factory()->create(['name' => 'Budi']);

        $this->assertDatabaseHas('users', ['name' => 'Budi']);
    }

    public function test_user_can_be_deleted(): void
    {
        $user = User::factory()->create(['name' => 'Siti']);
        $user->delete();

        $this->assertDatabaseMissing('users', ['name' => 'Siti']);
    }

    public function test_factory_makes_three_users(): void
    {
        User::factory()->count(3)->create();

        $this->assertDatabaseCount('users', 3);
    }
}

Run it with php artisan test:

   PASS  Tests\Feature\UserTest
  ✓ user can be created                                                  0.21s
  ✓ user can be deleted                                                  0.02s
  ✓ factory makes three users                                            0.02s

  Tests:    3 passed (3 assertions)
  Duration: 0.31s

The first test takes the longest, because it's the one that runs the migrations (files that hold the recipe for creating the tables).

RefreshDatabase: a clean counter for every test

It works in two steps:

  1. At the start of the run, only once, Laravel runs migrate:fresh: every table is deleted, then created again from the migrations.
  2. Each test is wrapped in a transaction (a set of changes that can be undone). As soon as the test finishes, that transaction is rolled back (undone), so whatever that test created is gone again.

The comparison below shows what the table users holds when each test's assertion runs, with and without RefreshDatabase:

When the assertion runs With RefreshDatabase Without RefreshDatabase
Test 1: assertDatabaseHas Budi (1 row) Budi (1 row)
Test 2: assertDatabaseMissing empty, Siti was deleted Budi
Test 3: assertDatabaseCount(3) 3 new users Budi + 3 new users = 4

Say the line use RefreshDatabase; is removed, and the tests use a database that keeps its data from one run to the next (such as a MySQL database kept for tests). The third test fails, because Budi from the first test is still there:

  ⨯ factory makes three users                                            0.03s
  ────────────────────────────────────────────────────────────────────────────
   FAILED  Tests\Feature\UserTest > factory makes three users
  Failed asserting that table [users] matches expected entries count of 3. Entries found: 4.
.

  at tests/Feature/UserTest.php:32
     28▕     public function test_factory_makes_three_users(): void
     29▕     {
     30▕         User::factory()->count(3)->create();
     31▕
  ➜  32▕         $this->assertDatabaseCount('users', 3);
     33▕     }
     34▕ }

Run it once more and the number becomes 8, because the previous run's data is still stored too. Tests whose result depends on the order and on leftover data like this are called leaky tests. With Laravel's default settings in the file phpunit.xml (SQLite :memory:, a database that exists only in memory), the result is different. Each test gets a new database with no tables, so every test fails with no such table: users, and no data is left for the next run.

Factory: a maker of sample data

A factory sets a default value for every column of one row of data, so a test only names the columns that matter to it. This is the User factory that comes with Laravel:

// database/factories/UserFactory.php (made by Laravel)
public function definition(): array
{
    return [
        'name' => fake()->name(),
        'email' => fake()->unique()->safeEmail(),
        'password' => static::$password ??= Hash::make('password'),
    ];
}

Database assertions

Assertion Passes when
assertDatabaseHas('users', ['name' => 'Budi']) there's a row with that value
assertDatabaseMissing('users', ['name' => 'Siti']) there's no row with that value
assertDatabaseCount('users', 3) the table holds exactly 3 rows
assertSoftDeleted('posts', ['id' => $post->id]) the row exists, but its deleted_at is filled (the row is marked as deleted, not removed)

Their failure messages show what's in the table. Say $user->delete() is forgotten in the second test. The message is:

  Failed asserting that a row in the table [users] does not match the attributes {
    "name": "Siti"
}.

Found similar results: [
    {
        "name": "Siti"
    }
].

Found similar results shows the rows that look like the one you checked for: here, Siti is still there. When assertDatabaseHas finds nothing in an empty table, its message ends with The table is empty.

RefreshDatabase, DatabaseTransactions, DatabaseMigrations

Trait What it does When
RefreshDatabase migrate:fresh once per run, then every test is rolled back the default choice
DatabaseTransactions only wraps every test in a transaction and rolls it back, without running migrations you already set up the test database yourself with the migrations
DatabaseMigrations runs the migrations again for every test rarely, it's the slowest

In the exercises: imitate the database yourself

The exercise sandbox runs plain PHP, without Laravel and without a database. So the "table" is only an array, and you write the assertions yourself:

class FakeDatabase
{
    public array $records = [];

    public function insert(array $data): bool
    {
        $this->records[] = $data;
        return true;
    }

    public function has(string $key, mixed $value): bool
    {
        foreach ($this->records as $row) {
            if ($row[$key] == $value) {
                return true;
            }
        }
        return false;
    }
}

⚠️ When the table doesn't hold what you expected

TL;DR: Put use RefreshDatabase; in the test class. Laravel then runs migrate:fresh (deletes all the tables and creates them again) once, before the first test. It rolls every test back (undoes its changes) when the test finishes, so every test starts from empty tables. Make data with a factory (a maker of sample data): User::factory()->create([...]) (saved), ->make() (not saved), or ->count(5)->create(). Check with assertDatabaseHas('users', [...]), assertDatabaseMissing('users', [...]) and assertDatabaseCount('users', 3), always with the table name first. Without RefreshDatabase, data leaks between tests: a count of 3 becomes 4, then 8. DatabaseTransactions only rolls back, without creating the tables again. In the exercise sandbox, the table is an array: add with $records[] = ..., search with foreach, count with count().

⚡ RefreshDatabase: a clean counter for every test

Write:

class UserTest extends TestCase
{
    use RefreshDatabase;
}
Guess first: use RefreshDatabase; cleans the database for every test. Say that in this class, the first test creates the user Budi, and the third test creates 3 users and then checks assertDatabaseCount('users', 3) (the table users holds exactly 3 rows). If the line use RefreshDatabase; is removed, what happens to the third test?

On a test database that keeps its data after the tests finish, it fails: it finds 4 rows, because Budi from the first test is still there. Run all the tests once more and the number becomes 8. On Laravel's default SQLite :memory: (a database in memory that is always new), every test fails with no such table: users.

Meaning: With RefreshDatabase, every test starts from empty tables.

⚡ Factories and database assertions

Write:

User::factory()->create(['name' => 'Budi']);

$this->assertDatabaseHas('users', ['name' => 'Budi']);

Meaning: User::factory() is a factory, a maker of sample data for the table users. create() makes one complete user and saves it, while make() only builds the object without saving it. In assertDatabaseHas, the table name comes first, then the array of columns and values that must be in one of the rows.

⚡ RefreshDatabase or DatabaseTransactions

Meaning: RefreshDatabase runs migrate:fresh once, before the first test: every table is deleted, then created again from the migrations (the recipes for the tables). After that, it rolls every test back (undoes its changes) when the test finishes. DatabaseTransactions only wraps every test in a transaction (a set of changes that can be undone) and rolls it back, without running migrations.

What you will learn