Skip to content

Instantly share code, notes, and snippets.

@jwhulette
Last active December 2, 2022 17:59
Show Gist options
  • Save jwhulette/e14317deccb8def8b7acceff25f8f595 to your computer and use it in GitHub Desktop.
Save jwhulette/e14317deccb8def8b7acceff25f8f595 to your computer and use it in GitHub Desktop.
[Refresh multiple databases]
<?php
declare(strict_types=1);
namespace Tests;
use Illuminate\Foundation\Testing\RefreshDatabase as FrameworkRefreshDatabase;
use Illuminate\Foundation\Testing\RefreshDatabaseState;
trait RefreshDatabase
{
use FrameworkRefreshDatabase {
refreshTestDatabase as frameworkRefreshTestDatabase;
}
/**
* Allow using the dump file during tests.
*/
// use FrameworkRefreshDatabase {
// migrateFreshUsing as protected originalMigrateFreshUsing;
// }
/**
* Refresh a conventional test database.
*
* This is a drop-in replacement for Laravel's `RefreshDatabase` testing trait. Do not use them together.
*
* We are having migrations targeting two different database connections. The default one "mysql" and another one
* named "addresses". The `migrate:fresh` command used in the original trait, only drops the tables the default
* connection. The `--database` option has no use here as it will cause all migrations run against that connection.
*
* To workaround the issue, this method calls drops the tables in additionally specified connections which should be
* stored in test class's `$connectionsToReset` property. Just as Laravel's `$connectionsToTransact` works.
*
* More information:
* https://github.com/laravel/framework/issues/21063
*
* @return void
*/
protected function refreshTestDatabase(): void
{
if (! RefreshDatabaseState::$migrated) {
$database = $this->app->make('db');
foreach ($this->connectionsToReset() as $connection) {
$database
->connection($connection)
->getSchemaBuilder()
->dropAllTables();
}
$this->artisan('migrate', ['--path' => 'tests/_migrations']);
}
$this->frameworkRefreshTestDatabase();
}
/**
* Allow using the dump file during tests.
*
* @see https://github.com/laravel/framework/issues/36294
*
* @return array<string,string>
*/
// protected function migrateFreshUsing(): array
// {
// return array_merge(
// [
// '--schema-path' => 'database/schema/mysql-schema.dump',
// ],
// $this->originalMigrateFreshUsing()
// );
// }
/**
* The database connections that should be reset before running `migrate:fresh` command.
*
* @return array
*/
protected function connectionsToReset(): array
{
return $this->connectionsToReset ?? [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment