Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rafaelogic's avatar

Multi-tenancy testing at snail's pace

I am using spatie laravel multi-tenancy package with livewire. I only have 56 tests and when I run phpunit it took at least 20 mins. to finish and at least 16 mins. when running with paratest.

This only happens after I implemented multi-tenancy as all tests finish less than a minute without it.

This is my TestCase.php code base.

<?php

namespace Tests;

use App\Models\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Spatie\Multitenancy\Concerns\UsesMultitenancyConfig;
use Spatie\Multitenancy\Events\MadeTenantCurrentEvent;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication, DatabaseTransactions, UsesMultitenancyConfig;

    protected function connectionsToTransact()
    {
        return [
            $this->landlordDatabaseConnectionName(),
            $this->tenantDatabaseConnectionName(),
        ];
    }

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

        config([
            'database.connections.landlord' => [
                'driver'    => 'sqlite',
                'database'  => ':memory:'
            ],

            'database.connections.tenant' => [
                'driver'    => 'sqlite',
                'database'  => ':memory:'
            ],
        ]);

        $this->setUpTenant();

        Event::listen(MadeTenantCurrentEvent::class, function () {
            $this->beginDatabaseTransaction();
        });
    }

    protected function tearDown(): void
    {
        DB::connection('tenant')->rollBack();
        DB::purge('tenant');

		Tenant::forgetCurrent();
        
        parent::tearDown();
    }

    public function setUpTenant(): void
    {
        if (! Tenant::checkCurrent()) {
            $this->artisan('migrate:fresh --database=landlord --path=database/migrations/landlord');

            $tenant = Tenant::factory()->create();

            $this->artisan("tenants:artisan 'migrate:fresh --path=database/migrations/tenant --database=tenant' --tenant={$tenant->id}");

            $tenant->makeCurrent();
        }
    }
}

0 likes
1 reply
tylernathanreed's avatar

If multi-tenancy is what slowed down your tests, then it's possible that switching tenants is somehow inefficient during tests.

I would recommend looking into what actions are performed when switching tenancy, and seeing if any of these are your bottleneck.

Please or to participate in this conversation.