To run your tests on a tenant database using the Tenancy for Laravel package, you need to ensure that your test environment is set up to switch to the tenant's database context. Here's a step-by-step guide to achieve this:
-
Set Up the Tenancy Environment: Ensure that your testing environment is configured to handle tenancy. This typically involves setting up the necessary database connections and configurations in your
phpunit.xmlorphpunit.xml.distfile. -
Use the Tenancy Testing Traits: The Tenancy package provides traits that help in setting up the tenant environment for testing. You can use these traits in your test classes.
-
Switch to Tenant Context: Before running your tests, you need to switch to the tenant's database context. This can be done by using the
tenancy()->initialize($tenant)method, where$tenantis the tenant model instance. -
Example Test Setup: Here's how you can modify your test class to run tests in a tenant context:
<?php
declare(strict_types=1);
namespace Tests\Feature\App\Notifications;
use App\Jobs\SendPushNotificationJob;
use App\Models\App\User;
use Illuminate\Support\Facades\Bus;
use Tests\TestCase;
use Stancl\Tenancy\Testing\TenantAwareTestCase;
use Stancl\Tenancy\Testing\InteractsWithTenants;
class SendPushNotificationJobTest extends TestCase
{
use TenantAwareTestCase, InteractsWithTenants;
protected function setUp(): void
{
parent::setUp();
// Create a tenant and initialize the tenant environment
$tenant = $this->createTenant();
tenancy()->initialize($tenant);
}
/**
* @test
*/
public function test_push_notification_job_is_dispatched()
{
// Fake the job
Bus::fake();
// Simulate notification creation
$tokens = ['fcm_token_1', 'fcm_token_2'];
$title = 'Test Notification';
$body = 'This is a test push notification.';
$data = ['notification_id' => 123];
// Dispatch the job
SendPushNotificationJob::dispatch($tokens, $title, $body, $data);
// Assert the job was dispatched with correct parameters
Bus::assertDispatched(SendPushNotificationJob::class, function ($job) use ($tokens, $title, $body, $data) {
return $job->tokens === $tokens &&
$job->title === $title &&
$job->body === $body &&
$job->data === $data;
});
}
// Other test methods...
}
- Run Your Tests: With the above setup, you can run your tests using PHPUnit, and they should execute within the tenant's database context.
By following these steps, you ensure that your tests are executed in the correct tenant environment, allowing you to test tenant-specific functionality effectively.