Summer Sale! All accounts are 50% off this week.

abkrim's avatar
Level 13

Sanctum testing a FormRequest class no work with authorized

Hello

Today I was trying to do some tests to check the authorize() method of a Request class in which I use the bouncer package.

When it failed, I did the basics of a couple of tests and I was surprised.

The controller has the method public function getProfile(ProfileUserFilterRequest $request)

the ProfileUserFilterRequest class in your authorize() method so you can check for the problem

public function authorize(): bool
{
    ray($this->user());

    ray(Bouncer::can('test-ability', $this->user()));

    return false;
}

Actually, if I test the controller this code works perfectly, indicating that the user who is accessing the endpoint has the ability to access that method, by returning Bouncer::can('test-ability', $this-> user()) the response true

However, when I want to do it to test only the form request the same code fails me, returning false because in reality, the $this->user is passed as null

## Controller level test

/** @test */
function users_needs_validate_authorization()
{
    // Viewer
    $user = User::factory()->create([
        'name' => 'Tester',
    ]);

    Bouncer::allow($user)->to('test-ability', $user);

    Sanctum::actingAs($user);

    $response = $this->withHeaders(['Accept' => 'application/json'])
        ->get('api/v2/profile');

    ray($response);
}

Request Level Test

/** @test */
function request_use_bouncer()
{
    $user = User::factory()->create([
        'name' => 'Tester',
    ]);

    Bouncer::allow($user)->to('test-ability', $user);

    Sanctum::actingAs($user);
    //$this->actingAs($user);  // Also not works

    $formRequest = new ProfileUserFilterRequest();

    ray($formRequest->authorize());
}

Now, $this->user() is null and of course Bouncer can not validate the ability

Appreciate help.

0 likes
0 replies

Please or to participate in this conversation.