Bird
Raised Fist0
Laravelframework~10 mins

Database testing (RefreshDatabase) in Laravel - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Database testing (RefreshDatabase)
Start Test
↓
RefreshDatabase Trait
↓
Run Database Migrations
↓
Execute Test Code
↓
Rollback or Reset DB
↓
Test Ends
This flow shows how the RefreshDatabase trait resets the database before each test by running migrations, ensuring a clean state.
Execution Sample
Laravel
<?php
use IlluminateFoundationTestingRefreshDatabase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_creation()
    {
        User::factory()->create();
        $this->assertDatabaseCount('users', 1);
    }
}
This test uses RefreshDatabase to reset the DB, creates a user, then checks the users table has exactly one record.
Execution Table
StepActionDatabase StateTest AssertionResult
1Start test methodEmpty databaseNo assertion yetContinue
2RefreshDatabase runs migrationsTables created, emptyNo assertion yetContinue
3User factory creates 1 userUsers table has 1 recordNo assertion yetContinue
4Assert users count is 1Users table has 1 recordAssertion passesContinue
5Test ends, database resetDatabase cleanedTest completeExit
💡 Test ends after assertion passes and database is reset for next test
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Database StateEmptyMigrations run, empty tablesUsers table: 1 userUsers table: 1 userCleaned/reset
Key Moments - 2 Insights
Why does the database get reset before each test?
The RefreshDatabase trait runs migrations fresh before each test (see execution_table step 2), so tests start with a clean database to avoid leftover data affecting results.
What happens if I create multiple users in one test?
Each user creation adds records to the database (like step 3). The database keeps these until the test ends and resets, so assertions can check exact counts during the test.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the database state after migrations run?
ADatabase is full of test data
BUsers table has 1 user
CEmpty tables created
DDatabase is not changed
💡 Hint
Check execution_table row 2 under Database State
At which step does the test check if the users table has exactly one record?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at execution_table row 4 under Test Assertion
If you remove RefreshDatabase trait, what would likely happen?
ATest might fail due to leftover data
BDatabase resets automatically anyway
CTest runs faster
DMigrations run twice
💡 Hint
Recall why RefreshDatabase resets DB before each test (see key_moments)
Concept Snapshot
Use RefreshDatabase trait in Laravel tests to reset the database before each test.
It runs migrations fresh, so tests start with a clean state.
Create test data inside tests, then assert database contents.
Database resets after test ends to avoid data leaks.
This ensures reliable, isolated database tests.
Full Transcript
In Laravel testing, the RefreshDatabase trait resets the database before each test by running migrations fresh. This means each test starts with an empty database with all tables created. When the test runs, you can create data like users using factories. Then you assert the database state, for example checking the number of users. After the test finishes, the database is cleaned again to prepare for the next test. This process avoids leftover data from one test affecting another, making tests reliable and isolated.

Practice

(1/5)
1. What is the main purpose of using the RefreshDatabase trait in Laravel tests?
easy
A. To seed the database with test data before tests run
B. To speed up tests by skipping database migrations
C. To reset the database after each test to ensure a clean state
D. To backup the database before running tests

Solution

  1. Step 1: Understand the role of RefreshDatabase

    The trait resets the database by running migrations fresh for each test.
  2. Step 2: Identify why resetting is important

    Resetting ensures tests do not affect each other by leftover data.
  3. Final Answer:

    To reset the database after each test to ensure a clean state -> Option C
  4. Quick Check:

    Database reset = Clean test state [OK]
Hint: Remember: RefreshDatabase cleans database for every test [OK]
Common Mistakes:
  • Thinking it seeds data automatically
  • Confusing it with speeding up tests
  • Assuming it backs up data
2. Which of the following is the correct way to use RefreshDatabase in a Laravel test class?
easy
A. class ExampleTest extends TestCase { implements RefreshDatabase }
B. class ExampleTest extends TestCase { RefreshDatabase(); }
C. class ExampleTest extends TestCase { @RefreshDatabase }
D. class ExampleTest extends TestCase { use RefreshDatabase; }

Solution

  1. Step 1: Recall trait usage syntax in PHP

    Traits are included using the use keyword inside the class body.
  2. Step 2: Match syntax with options

    Only class ExampleTest extends TestCase { use RefreshDatabase; } correctly uses use RefreshDatabase; inside the class.
  3. Final Answer:

    class ExampleTest extends TestCase { use RefreshDatabase; } -> Option D
  4. Quick Check:

    Traits use use keyword inside class [OK]
Hint: Traits use 'use' keyword inside class body [OK]
Common Mistakes:
  • Using parentheses like a method call
  • Using annotations instead of traits
  • Trying to implement traits as interfaces
3. Given this Laravel test code snippet using RefreshDatabase:
public function test_user_creation() {
    User::factory()->create(['name' => 'Alice']);
    $this->assertDatabaseHas('users', ['name' => 'Alice']);
}
What will happen if you run this test twice in a row?
medium
A. Both tests pass because the database is reset each time
B. The second test fails due to duplicate user entries
C. Both tests fail because the database is not migrated
D. The first test passes, second test errors out with connection issue

Solution

  1. Step 1: Understand RefreshDatabase effect

    It resets the database before each test, so no leftover data remains.
  2. Step 2: Analyze test behavior on repeated runs

    Each test run starts fresh, so creating 'Alice' user and asserting passes every time.
  3. Final Answer:

    Both tests pass because the database is reset each time -> Option A
  4. Quick Check:

    Database reset = independent test runs [OK]
Hint: RefreshDatabase resets DB so repeated tests stay clean [OK]
Common Mistakes:
  • Assuming data persists between tests
  • Thinking duplicate entries cause failure
  • Confusing RefreshDatabase with no migration
4. You wrote a Laravel test using RefreshDatabase but the database is not resetting between tests. What is the most likely cause?
medium
A. You did not call migrate:fresh manually before tests
B. You forgot to add use RefreshDatabase; trait in your test class
C. You used RefreshDatabase but did not seed the database
D. You ran tests without the --database option

Solution

  1. Step 1: Check trait usage in test class

    Without adding use RefreshDatabase;, the trait's reset logic won't run.
  2. Step 2: Understand that manual migration commands are not needed

    The trait handles migrations automatically; manual commands are unnecessary.
  3. Final Answer:

    You forgot to add use RefreshDatabase; trait in your test class -> Option B
  4. Quick Check:

    Trait must be included to reset DB [OK]
Hint: Always add trait with 'use RefreshDatabase;' inside test class [OK]
Common Mistakes:
  • Thinking manual migration commands are required
  • Confusing seeding with resetting
  • Assuming command line options affect trait behavior
5. You want to write a Laravel test that uses RefreshDatabase but also seeds some initial data before each test. Which approach is correct?
hard
A. Use RefreshDatabase trait and call $this->seed() in the test's setUp() method
B. Use RefreshDatabase trait and add seeder class name as a parameter to the trait
C. Manually run php artisan migrate:fresh --seed before running tests
D. Use RefreshDatabase trait and override the refreshDatabase() method to seed

Solution

  1. Step 1: Understand how to seed with RefreshDatabase

    The trait resets the database, but seeding must be triggered manually in tests.
  2. Step 2: Use $this->seed() in setUp() method

    This ensures seeding runs before each test after database reset.
  3. Final Answer:

    Use RefreshDatabase trait and call $this->seed() in the test's setUp() method -> Option A
  4. Quick Check:

    Seed manually after refresh in setUp() [OK]
Hint: Call $this->seed() in setUp() when using RefreshDatabase [OK]
Common Mistakes:
  • Trying to pass seeder to trait directly
  • Running artisan commands manually during tests
  • Overriding trait methods unnecessarily