Laravel testing - UnauthorizedException: User does not have the right roles

2.5k Views Asked by At

So I'm working with laravel tests and I'm making tests for accessing users page where I can see all the users and edit them. In the UsersController.php i have made that only admin can access the user's page. The roles and permissions I've used from spatie plugin https://github.com/spatie/laravel-permission. I've made the test to check if a simple user can access the user's page and here's the code in UserTest.php

/** @test */
public function user_try_to_access_users_page()
{
    $user = factory(User::class)->create();
    $user->assignRole('user');
    $this->actingAs($user);

    $response = $this->get('/users');
    $response->assertStatus(403);
}

And here is the code in UsersController.php thas allows only admin to access it.

public function index()
{
    $testUser = Auth::user();

    if ($testUser->hasRole('admin')) 
    {   
        $users = User::all();

        return view('users.index', ['users' => $users]);
    }

    return response(view('errors.403'), 403);
}

Now when I try to run the test it's giving me the error

Tests\Feature\UserTest::user_try_to_access_users_page Spatie\Permission\Exceptions\UnauthorizedException: User does not have the right roles.

In this line $response = $this->get('/users');.

This is good because in not letting the user to access the page but it should give the code 403 and not the error. Thank you for your time.

1

There are 1 best solutions below

0
On

For anyone still looking for a solution, it is not to remove the permission check from the constructor as @aynber suggested in the comments, since that defeats the purpose.

When making the request in the feature test, just add the Accept header with the value of application/json so that instead of throwing an exception, an HTTP 403 error code is returned.

$response = $this->get('/users', [
    'Accept': 'application/json'
]);