sh1r3f's avatar

How to write tests to my stancl multitenancy app?

This sounds like a non-specific question. but yes it it.. I can't find the stancl/tenancy documentation for testing useful so can someone refer me to a good docs or article explaining how can I implement stancl/tenancy while testing? Thanks in advance.

0 likes
4 replies
tisuchi's avatar

@sh1r3f Testing a multi-tenancy application can be a bit tricky, as you need to make sure that the tenant is properly set up and switched for each test. Here are some general steps you can take to write tests for your stancl/tenancy app:

  1. Set up your test environment: Make sure you have a testing database set up and that your tests are configured to use it.

  2. Create a test tenant: Create a test tenant in your testing database, so that you can test your application's tenant-specific functionality.

  3. Switch to the tenant in your tests: Use the Tenancy facade provided by the stancl/tenancy package to switch to the test tenant before running each test. This will ensure that the tenant is properly set up and that all database queries are executed within the context of the tenant.

  4. Write your tests: Write your tests as you would normally, making sure to take into account any tenant-specific functionality.

  5. Run your tests: Run your tests to make sure that everything is working as expected.

Here are some example of test set up:

use Stancl\Tenancy\Facades\Tenancy;

public function setUp(): void
{
    parent::setUp();

    // Create a test tenant.
    $tenant = Tenancy::createTenant([
        'domain' => 'test.localhost',
    ]);

    // Switch to the tenant.
    Tenancy::setTenant($tenant);
}
kei_mx's avatar

Hello 👋.

I had the same situation when I built a multitenant application. Then I created a custom test case to run tests in both the tenant and landlord contexts, and later I turned it into a package.

The package provides a comprehensive base test case with automatic tenant database isolation, configuration management, and helper methods to simplify testing in multi-tenant environments built with Spatie Laravel Multitenancy.

https://github.com/ArmCM/laravel-tenancy-testing

I hope this helps! I’d really appreciate any feedback or suggestions.

kei_mx's avatar

For now, it is only compatible with PHPUnit. However, making it compatible with Pest will be great.

Please or to participate in this conversation.