Skip to content

Instantly share code, notes, and snippets.

@mortenscheel
Created October 6, 2023 09:59
Show Gist options
  • Save mortenscheel/332f15c04cc91fe8549aed066f73bfdf to your computer and use it in GitHub Desktop.
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.
<?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