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

lalitesh's avatar

Feature Test using Spatie's Laravel-permission package

I am testing my User API controller that uses Spatie's Laravel-permission package and has teams feature enabled.

Here is my method:

public function test_index_returns_all_models()
{
    // Reset cached roles and permissions
    app()['cache']->forget('spatie.permission.cache');

    //Mock admin login
    $admin = User::factory()->create();



    $team = $admin->ownedTeams()->save(Team::forceCreate([
        'user_id' => $admin->id,
        'name' => 'Admin Team2',
        'personal_team' => true,
    ]));


     // temporary: get session team_id for restore at end
     $session_team_id = getPermissionsTeamId();

     // set actual new team_id to package instance
     setPermissionsTeamId($team);

    // Create permissions & role for superadmin
    $allPermission = Permission::create(['guard_name' => 'web', 'name' => 'all-permissions']);
    $superadminRole = Role::create(['guard_name' => 'web', 'name' => 'superadmin5', 'team_id' => $team->id]);
    $superadminRole->givePermissionTo($allPermission);

    $admin->assignRole($superadminRole);
    setPermissionsTeamId($session_team_id);

    $this->actingAs($admin);

    // Create 3 User models
    $models = User::factory()->count(3)->create();

    $response = $this->get('/api/users');
    $response->assertStatus(200);

    // Assert the structure of the JSON response
    $response->assertJsonStructure([
        'data',
        'links' => [
            'first',
            'last',
            'prev',
            'next',
        ],
        'meta' => [
            'current_page',
            'from',
            'last_page',
            'links' => [
                '*' => [
                    'url',
                    'label',
                    'active',
                ]
            ],
            'path',
            'per_page',
            'to',
            'total',
        ]
    ]);

    // Assert that the response data contains the expected models
    foreach ($models as $model) {
        $response->assertJsonFragment($model->toArray());
    }
}

My UserPolicy class a pre-authorization check as well:

/**
     * Perform pre-authorization checks.
     */
    public function before(User $user, string $ability): bool|null
    {
        if ($user->can('all-permissions')) {
            return true;
        }

        return null;
    }

Since I am assigning a permission "all-permission" to my admin user, I am expecting 200, however I am receiving 403 error.

0 likes
0 replies

Please or to participate in this conversation.