Hello everyone,
I'm facing an intermittent issue with a Pest test in a FilamentPHP project. The test sometimes passes and sometimes fails, without any code changes between runs. Here's the situation:
The test:
it('can render index page', function (): void {
asAdmin();
$this->get(UserResource::getUrl())
->assertSuccessful();
});
✅ Sometimes:
PASS Tests\Feature\Filament\UserResource\ListUsersTest
✓ it can render index page
❌ Other times:
FAILED Tests\Feature\Filament\UserResource\ListUsersTest > it can render index page
Expected response status code [>=200, <300] but received 403.
Failed asserting that false is true.
at tests\Feature\Filament\UserResource\ListUsersTest.php:14
Helper method on Pest.php:
function asAdmin(): TestCase
{
$user = User::factory()->create([
'role' => Role::Admin->value,
]);
return test()->actingAs($user);
}
UserPolicy:
public function viewAny(User $user): bool
{
return $user->role === Role::Admin;
}
All other policy methods check for the same condition: role === Role::Admin.
User model casts:
protected function casts(): array
{
return [
'role' => Role::class,
...
];
}
What I’ve tried:
- Confirmed the enum cast works fine.
- Confirmed the role is being set correctly.
- Inspected the response with
dump() when it fails, it shows the default Laravel 403 HTML page.
- Cleared caches, config, route, view, etc.
What could be causing this random behavior?
It’s like sometimes the policy check is skipped or misinterpreted, possibly due to request context, timing, or test isolation? Could it be related to session state, middleware, or how Filament bootstraps resources during tests?
Has anyone experienced something similar with Pest + Filament? Would appreciate any leads or debugging strategies 🙏