diff --git a/assets/config.php b/assets/config.php index a9fd2b92..92350465 100644 --- a/assets/config.php +++ b/assets/config.php @@ -196,4 +196,6 @@ return [ '--class' => 'DatabaseSeeder', // root seeder class // '--force' => true, // This needs to be true to seed tenant databases in production ], + + 'test_tenant' => env('TEST_TENANT', 1), ]; diff --git a/src/Testing/TenantAwareTestCase.php b/src/Testing/TenantAwareTestCase.php new file mode 100644 index 00000000..fe9ce081 --- /dev/null +++ b/src/Testing/TenantAwareTestCase.php @@ -0,0 +1,71 @@ +tenancy) { + $this->initializeTenancy(); + } + } + + /** + * Initialize tenancy for a specific tenant. + * + * @param string|int|null $tenantIdentifier + * @return void + */ + protected function initializeTenancy(string|int|null $tenantIdentifier = null): void + { + $identifier = $tenantIdentifier ?? config('tenancy.test_tenant'); + + $this->tenant = Tenant::find($identifier); + + if (! $this->tenant) { + $this->fail("Tenant [{$identifier}] not found. Please ensure TEST_TENANT is set correctly in .env.testing or config('tenancy.test_tenant')."); + } + + tenancy()->initialize($this->tenant); + } + + /** + * Run assertions or actions in central context. + */ + protected function runInCentralContext(callable $callback): mixed + { + $tenant = $this->tenant ?? tenancy()->tenant; + + tenancy()->end(); + + try { + return $callback(); + } finally { + if ($tenant) { + tenancy()->initialize($tenant); + } + } + } +}