Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active October 18, 2022 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/db4277e16647981cac91e428a9c8e2a9 to your computer and use it in GitHub Desktop.
Save ziadoz/db4277e16647981cac91e428a9c8e2a9 to your computer and use it in GitHub Desktop.
Refresh Database Using Specific Database Connection In Laravel Tests
<?php
namespace Tests\Feature;
use Tests\RefreshesDatabase;
class ExampleTest
{
use RefreshesDatabase;
public string $connectionToMigrate = 'mysql-elevated';
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\RefreshDatabase as LaravelRefreshDatabase;
// Use a specific database connection for test migrations.
// @see: https://github.com/laravel/framework/pull/44630
// @see: https://github.com/laravel/framework/issues/36294
trait RefreshDatabase
{
use LaravelRefreshDatabase {
migrateFreshUsing as protected migrateFreshUsingDefaults;
}
protected function migrateFreshUsing()
{
$database = $this->connectionToMigrate();
return array_merge(
$this->migrateFreshUsingDefaults(),
$database ? ['--database' => $database] : [],
);
}
protected function connectionToMigrate(): string|bool
{
return property_exists($this, 'connectionToMigrate') ? $this->connectionToMigrate : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment