Created
October 6, 2023 09:59
-
-
Save mortenscheel/332f15c04cc91fe8549aed066f73bfdf to your computer and use it in GitHub Desktop.
A replacement for Laravel's LazilyRefreshDatabase trait that only runs migrate:fresh if necessary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use Illuminate\Contracts\Console\Kernel; | |
use Illuminate\Foundation\Testing\RefreshDatabase; | |
use Illuminate\Foundation\Testing\RefreshDatabaseState; | |
trait LazilyRefreshDatabaseIfNecessary | |
{ | |
use RefreshDatabase { | |
refreshDatabase as baseRefreshDatabase; | |
} | |
/** | |
* Define hooks to migrate the database before and after each test. | |
* | |
* @return void | |
*/ | |
public function refreshDatabase(): void | |
{ | |
$database = $this->app->make('db'); | |
$database->beforeExecuting(function() { | |
if (RefreshDatabaseState::$lazilyRefreshed) { | |
return; | |
} | |
RefreshDatabaseState::$lazilyRefreshed = true; | |
$this->baseRefreshDatabase(); | |
}); | |
$this->beforeApplicationDestroyed(function() { | |
RefreshDatabaseState::$lazilyRefreshed = false; | |
}); | |
} | |
protected function refreshTestDatabase(): void | |
{ | |
if (!RefreshDatabaseState::$migrated) { | |
if ($this->shouldMigrate()) { | |
$this->artisan('migrate:fresh', $this->migrateFreshUsing()); | |
} | |
$this->app[Kernel::class]->setArtisan(null); | |
RefreshDatabaseState::$migrated = true; | |
} | |
$this->beginDatabaseTransaction(); | |
} | |
protected function shouldMigrate(): bool | |
{ | |
// Check if there are pending migrations | |
// Perform additional checks as required | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment