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

somenet77's avatar

Make test case for resource with role and permission.

I have created a test case for

it('can list games', function () {
    $games = Game::factory()->count(10)->create();

    livewire(GameResource\Pages\ListGames::class)->assertCanSeeTableRecords($games);
});

This resource is guarded by spatie role and permission. This works fine if I remove the role and permission package. But not work with the role and permission package.

 FAILED  Tests\Feature\GameTest > it can list games                                                                                                                                                                                 Error   
  Call to a member function getTableRecordKey() on null

0 likes
3 replies
zufflie's avatar

You can create a user and their roles and then use the actingAs($user) Method. So you will be acting as a User. Making it reusable when you define it in the Pest.php File.

For an Admin Example.

{
 function asAdmin()
{

    $adminRole = Role::firstOrCreate(['id' => 1, 'title' => 'admin']);
    $user = User::factory()->create();
    $user->roles()->attach($adminRole->id);

    test()->actingAs($user);

    return $user;
}

In your Tests you can just call asAdmin() before you make the Livewire Assertion. 

Please or to participate in this conversation.