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

Cobs's avatar
Level 1

Should I test my permissions in Feature tests ?

Hello,

I use policies to check if a user is allowed to use a specific API route. Should I bother testing permissions with a Feature test.

Well, obviously, my permissions should be tested but I can't find an easy way to setup or mock the permission system other than creating the whole fixture into the database. Moreover the policy class is already unit tested.

Any idea about how to test the permissions from a user perspective ?

0 likes
2 replies
martinbean's avatar
Level 80

@cobs I don’t really know how you’ve set your permissions up but yeah, it’s usually a good idea to test users with different roles and asserting the responses (whether the user should be able to perform the request or not).

If you just have simple name-based roles then you can use data providers and a test case something like:

public function testCreatePost(string $role, bool $hasPermission): void
{
    $user = User::factory()->create([
        'role' => $role,
    ]);

    $response = $this->actingAs($user)->postJson('/api/posts', [
        'title' => 'Test Post Title',
        'body' => 'This is a test post.',
    ]);

    if ($hasPermssion) {
        $response->assertCreated();
    } else {
        $response->assertUnauthorized();
    }
}

public function userRolesDataProvider(): array
{
    return [
        'customer' => ['customer', false],
        'moderator' => ['moderator', true],
        'administrator' => ['administrator', true],
    ];
}

You‘d obviously change this to however you actually are creating roles and permissions in your application, but it should be enough to get you started.

Cobs's avatar
Level 1

Well... my users can have multiples roles and permissions on each role can be modified but yeah. Sounds ok

Please or to participate in this conversation.