Thorgram's avatar

How to test a redirect for ressource route

Hello.

I'm currently implementing testing in a pretty big application.

I'm still at the start and i would like some advice on a problem :

How do you test the redirection for a group of routes.

For example, in the app, only admins can navigate to the user CRUD. The routes for the controller are always prefixed with "/admin/users/".

Do i need to test every route in the controller to be sure a user gets redirected each time ?

And then i have roles on the admin, and they are redirected too on some routes. Do i also test every routes for them ?

Thanks.

0 likes
4 replies
NOMGUY's avatar

we use 'prefix' and for authenticity we use 'middleware' if you know what i mean

Thorgram's avatar

Yes, thank you. I should clarify a bit more my question.

I have some CRUDs controller ( let's take the UserController for instance ).

Every CRUD has custom limitations depending on roles, and this is handled in the middleware.

The application is functionning as intended.

My question is more on how to test via PHPUnit that when they navigate to the route the middleware is called ?

And in my example, the standard users have the same redirection on every method of this controller.

But some users have access to only some methods. Shoud i test the redirect in my Feature test for each role not having access to the method ?

Thanks.

devfrey's avatar
devfrey
Best Answer
Level 11

Personally, I would be as explicit as possible in tests. Specify every route and role. You can use PHPUnit's data providers to loop through multiple datasets.

The easiest way would be to test the route's response. Laravel's test suite provides you with a TestResponse instance after using the built-in get(), post(), etc. methods. The TestResponse class has a method called assertRedirect(), so a simple test could look like this:

/**
  * @dataProvider routesDataProvider
  */
public function testAdminRoutesRequireAdminRole($route, $method) {
    // Either don't authenticate or authenticate with a user that has insufficient permissions
    $this->call($method, $route)
        ->assertRedirect('/access-denied');
}

public function routesDataProvider() {
    return [
        ['/admin/page', 'GET'],
    ];
}

1 like
munazzil's avatar

In your console type below and you can check every routes and middleware.

php artisan route:list

Please or to participate in this conversation.