Skip to content
Advertisement

How to seed database migrations for laravel tests?

Laravel’s documentation recommends using the DatabaseMigrations trait for migrating and rolling back the database between tests.

use IlluminateFoundationTestingDatabaseMigrations;

class ExampleTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->get('/');

        // ...
    }
}

However, I’ve got some seed data that I would like to use with my tests. If I run:

php artisan migrate --seed

then it works for the first test, but it fails subsequent tests. This is because the trait rolls back the migration, and when it runs the migration again, it doesn’t seed the database. How can I run the database seeds with the migration?

Advertisement

Answer

With Laravel 8, if you’re using the RefreshDatabase trait you can invoke seeding from your test case using below:

use IlluminateFoundationTestingRefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        // Run the DatabaseSeeder...
        $this->seed();

        // Run a specific seeder...
        $this->seed(OrderStatusSeeder::class);

        $response = $this->get('/');

        // ...
    }
}

see docs for more information/examples: https://laravel.com/docs/8.x/database-testing#running-seeders

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement