I’m currently building a multi-tenant application using stancl/tenancy
(every tenant uses their own database) in my Laravel application.
Whenever I’m writing tests, tests fail a lot due to the error
IlluminateDatabaseQueryException: SQLSTATE[55006]: Object in use: 7 FEHLER: auf Datenbank »tenant_019949ce« wird von anderen Benutzern zugegriffen
DETAIL: 1 andere Sitzung verwendet die Datenbank. (Connection: tenant_host_connection, SQL: DROP DATABASE "tenant_019949ce")
which means the table is used by another user. Tables are created when a tenant is created and should be deleted if a tenant gets deleted but it always fails in tearDown
method.
My tests extend TenancyTestCase
class:
use IlluminateFoundationTestingTestCase as BaseTestCase;
class TenancyTestCase extends BaseTestCase {
use RefreshDatabase;
private Tenant $tenant;
protected function setUp(): void {
parent::setUp();
Config::set('tenancy.seeder_parameters.--class', TestDatabaseSeeder::class);
$this->setupDefaultTenant();
$this->forceRootUrl();
$this->withoutVite();
}
private function setupDefaultTenant(): void {
$this->tenant = Tenant::factory()->create();
$this->tenant->domains()->save(Domain::factory([
'domain' => 'tenant',
])->make());
tenancy()->initialize($this->tenant);
}
private function forceRootUrl(): void {
$parsed = parse_url(config('app.url'));
$host = $parsed['host'] ?? 'localhost.test';
$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
URL::forceRootUrl('https://tenant.' . $host . $port);
}
public function tearDown(): void {
tenancy()->end();
$this->tenant->delete();
parent::tearDown();
}
}
I couldn’t figure out why yet, any ideas on how to fix this?
My goal is to create a single database for each test and delete them if test is completed.
Thank you.