Skip to content

Instantly share code, notes, and snippets.

@JohnRoux
Created May 2, 2025 11:47
Show Gist options
  • Save JohnRoux/7e7f622fbbc4a09877f068579309d72d to your computer and use it in GitHub Desktop.
Save JohnRoux/7e7f622fbbc4a09877f068579309d72d to your computer and use it in GitHub Desktop.
Custom RefreshDatabase trait -> Wipe DB, start from single dump -> migrate -> seed. Only reseed if migrations have changed
<?php
namespace Tests;
use Exception;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\RefreshDatabase as BaseRefreshDatabase;
use Illuminate\Foundation\Testing\RefreshDatabaseState;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
trait RefreshDatabase
{
use BaseRefreshDatabase;
protected function refreshTestDatabase()
{
RefreshDatabaseState::$migrated = $this->checkIfMigrationsHaveRun();
if (RefreshDatabaseState::$migrated === false) {
Artisan::call('db:wipe', [
'--database' => 'mysql',
'--force' => true,
]);
DB::unprepared(file_get_contents(database_path('test_migration_seed_2024_01_17.sql')));
$this->artisan('migrate', ['--seed' => '1']);
$this->app[Kernel::class]->setArtisan(null);
RefreshDatabaseState::$migrated = true;
}
$this->beginDatabaseTransaction();
}
protected function checkIfMigrationsHaveRun()
{
try {
$migrator = app('migrator');
$ran = $migrator->getRepository()->getRan();
foreach ($migrator->getMigrationFiles($migrator->paths()) as $migrationFile) {
if (! in_array($migrator->getMigrationName($migrationFile), $ran, true)) {
return false;
}
}
return true;
} catch (Exception $e) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment