timroush's avatar

Manually Seed RefreshDatabase

I'm running some migrations with SQLite, and my tests are using the RefreshDatabase trait. I also have seeders (registered in the DatabaseSeeder.php file) that should seed my tables. However, when I run my tests, the migrated databases are empty. That said, when I edit the RefreshDatabase trait to seed, it works fine:

protected function refreshTestDatabase()
    {
        if (! RefreshDatabaseState::$migrated) {
            dump("Migrating DB in trait");
            $this->artisan('migrate:fresh', $this->shouldDropViews() ? [
                '--drop-views' => true,
            ] : []);

            $this->artisan('db:seed');

            $this->app[Kernel::class]->setArtisan(null);

            RefreshDatabaseState::$migrated = true;
        }

        $this->beginDatabaseTransaction();
    }

(Note the added $this->artisan('db:seed');)

I feel like there should be a way to run the Seeders without editing the core, but for the life of me I'm not sure why this is the thing that solves my problem. I'm running Laravel 5.6 on PHP 7.2 FWIW.

0 likes
4 replies
realrandyallen's avatar

Use a setUp function in any test class you want the db seeded:

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function setUp()
    {
        parent::setUp();

        $this->artisan('db:seed');
   }

   /** @test */
   public function it_does_stuff()
   {

   }

   ...
PatrickSJ's avatar

In the setup you can call DatabaseSeeder as follows:

public function setUp() {
    parent::setUp();

    $this->seed(DatabaseSeeder::class);
}

Kainam's avatar

I have a specific question about this. I'm running my tests against MySql and I found that for tests that use seeding the clean-up after the test fails. So I end up with some left over records that cause certain other tests to fail.

lukmauu's avatar

For me I just added public $seed = true; on the test class, if you look inside the trait it looks fo this flag and if you set to true it will migrate and seed.

2 likes

Please or to participate in this conversation.