This seems to seed before every single test, which is perhaps not ideal.
It was mentioned in the original answer, that we could override the refreshTestDatabase method to add in a seed. That's what I do, and it means it will seed just once, right after the first set of migrations.
Depending on the amount of seeders you have, this can be a big performance gain for your tests.
<?php
namespace Tests\Traits;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\RefreshDatabaseState;
trait RefreshDatabaseWithSeeds
{
use RefreshDatabase;
/**
* Refresh the in-memory database.
*
* @return void
*/
protected function refreshInMemoryDatabase()
{
$this->artisan('migrate');
$this->artisan('db:seed');
$this->app[Kernel::class]->setArtisan(null);
}
/**
* Refresh a conventional test database.
*
* @return void
*/
protected function refreshTestDatabase()
{
if (! RefreshDatabaseState::$migrated) {
$this->artisan('migrate:fresh', $this->shouldDropViews() ? [
'--drop-views' => true,
] : []);
$this->artisan('db:seed');
$this->app[Kernel::class]->setArtisan(null);
RefreshDatabaseState::$migrated = true;
}
$this->beginDatabaseTransaction();
}
}
This will allow you to use RefreshDatabaseWithSeeds; in your extended TestCase, instead of use RefreshDatabase, and will therefore run the seeders only once.
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Tests\Traits\RefreshDatabaseWithSeeds;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, RefreshDatabaseWithSeeds;
}