F
Filament2mo ago
Simone

Testing tenant-aware resources in v4

What I am trying to do: I'm trying to test the creation of a tenant-aware resource. I've just updated my application from version 3 following the upgrade guide. The tests were working fine before the update, but now I'm getting an error related to a missing tenant ID in insert queries. What I did: I've read the new information about multi-tenancy (https://filamentphp.com/docs/4.x/users/tenancy#tenancy-security). I now understand that there is a middleware that automatically manages queries, but, since I'm coming from version 3, my models are manually managed to the tenant.
This shouldn't be a problem, because I've checked the code and seen that if the scope is already applied, nothing should happen. I've got no issues with browser requests, though, so I think there is probably something missing or wrong in the instructions. My issue/the error:
NOT NULL constraint failed: customers.tenant_id ...
NOT NULL constraint failed: customers.tenant_id ...
Code:
it('can create a customer', function () {
$customer = Customer::factory()->make();

livewire(CreateCustomer::class)
->fillForm([
'type' => $customer->type,
'first_name' => $customer->first_name,
'last_name' => $customer->last_name,
])
->call('create')
->assertHasNoFormErrors();

assertDatabaseHas('customers', [
'type' => $customer->type,
'first_name' => $customer->first_name,
'last_name' => $customer->last_name,
]);
});
it('can create a customer', function () {
$customer = Customer::factory()->make();

livewire(CreateCustomer::class)
->fillForm([
'type' => $customer->type,
'first_name' => $customer->first_name,
'last_name' => $customer->last_name,
])
->call('create')
->assertHasNoFormErrors();

assertDatabaseHas('customers', [
'type' => $customer->type,
'first_name' => $customer->first_name,
'last_name' => $customer->last_name,
]);
});
2 Replies
Simone
SimoneOP2mo ago
I forgot to mention that I've overridden the setUp method of the TestCase class to set the tenant before every test
protected function setUp(): void
{
parent::setUp();

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

$this->actingAs($user);

Filament::setTenant($tenant);
Filament::setCurrentPanel('admin');
}
protected function setUp(): void
{
parent::setUp();

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

$this->actingAs($user);

Filament::setTenant($tenant);
Filament::setCurrentPanel('admin');
}
Dennis Koch
Dennis Koch2mo ago
If you are not using Filaments build-in logic, how are you setting the current tenant id for new models?

Did you find this page helpful?