2

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Check to see if the route is using the role middleware. It may be hitting that before it hits your function. – aynber Nov 23 '18 at 13:23
  • In the routes im using only auth middleware to check if the user is logged in but in the UsersController.php constructor i declared $this->middleware(['role:admin']); – Ardit Imeri Nov 23 '18 at 13:30
  • That would probably do it. Remove it from the constructor and try again. – aynber Nov 23 '18 at 13:35
  • @aynber Well that was easier than i expected! Thank you and have a nice day – Ardit Imeri Nov 23 '18 at 13:39

1 Answers1

0

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'
]);

Abbas
  • 1,118
  • 1
  • 11
  • 25