Created
May 23, 2025 15:28
-
-
Save ziadoz/ccaf5e95d260f1f56282b059496b840a to your computer and use it in GitHub Desktop.
Laravel 12 - Custom Connection for Parallel Testing
This file contains hidden or 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 App\Providers; | |
use Illuminate\Support\Facades\Artisan; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Testing\Concerns\TestDatabases; | |
use Illuminate\Testing\ParallelTestingServiceProvider as LaravelParallelTestingServiceProvider; | |
// Laravel doesn't support changing the database connection when running tests in parallel, so we have to override the relevant method. | |
// @see: https://sarahjting.com/blog/laravel-paratest-multiple-db-connections | |
class ParallelTestingServiceProvider extends LaravelParallelTestingServiceProvider | |
{ | |
use TestDatabases { | |
switchToDatabase as protected switchToDatabaseDefault; | |
} | |
protected string $connectionToParaTest = 'my-connection'; // Your custom connection. | |
protected function ensureSchemaIsUpToDate(): void | |
{ | |
if (! self::$schemaIsUpToDate) { | |
Artisan::call('migrate', ['database' => $this->connectionToParaTest]); | |
self::$schemaIsUpToDate = true; | |
} | |
} | |
protected function switchToDatabase($database): void | |
{ | |
config()->set('database.default', $this->connectionToParaTest); | |
$this->switchToDatabaseDefault($database); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment