Enhancing Filament Resource Testing with Pest and Tenant Awareness

Introduction

The Reimpact/platform project is undergoing improvements to its testing infrastructure, specifically focusing on Filament resources. The goal is to ensure comprehensive test coverage for CRUD operations across various resources, while also addressing tenant-specific data handling.

The Challenge

Previously, testing Filament resources lacked sufficient coverage, especially when dealing with tenant-specific data. The application utilizes a multi-tenant architecture, requiring tests to accurately reflect data isolation and access control based on the current tenant. This involved ensuring that factories correctly handle company_id assignment and that validations properly account for tenant-specific rules.

The Solution

Comprehensive Pest tests were added for Filament resources, including Brand, Product, Material, Warehouse, Recipe, Sale, Purchase, Rate, MassiveUpload, and GeneratedReport. These tests cover list, create, validate, edit, update, and delete operations.

use App\Models\Product;
use Filament\Facades\Filament;
use function Pest\Livewire\livewire;

it('can list products', function () {
    Filament::setContext('filament');
    $this->actingAs(User::factory()->create());

    $product = Product::factory()->create();

    livewire(ProductResource\Pages\ListProducts::class)
        ->assertSee($product->name);
});

Key Improvements

  1. Pest Integration: Adoption of Pest for cleaner and more expressive tests.
  2. Tenant Context Handling: Factories were modified to conditionally set company_id based on the current TenantContext, ensuring accurate data creation for both tenant and public tables.
  3. Validation Fixes: Date validation rules in Material and Recipe resources were updated to use Filament's beforeOrEqual and afterOrEqual methods, providing better integration with Filament's form handling.
  4. Global Scope Adjustments: The Rate model's HasTenantTable trait was removed, reflecting that rates are global and not tenant-scoped.

Results

  • Increased test coverage for Filament resources, leading to more robust and reliable CRUD operations.
  • Improved tenant data handling in tests, ensuring accurate data isolation and access control.
  • Simplified validation rules with Filament's built-in methods.

Lessons Learned

When working with multi-tenant applications, it's crucial to ensure that tests accurately reflect data isolation and access control. Utilizing framework-specific validation methods and adapting factories to handle tenant contexts can significantly improve the reliability and accuracy of tests. Remember to review model scopes and ensure they align with the intended data access patterns.

Enhancing Filament Resource Testing with Pest and Tenant Awareness
GERARDO RUIZ

GERARDO RUIZ

Author

Share: