GodziLaravel's avatar

is it possible to test if all routes are redirected to login page when user is not logged-id ?

Hello ,

Here bellow I made a test to know if a non-loged user when he request / is redirected to the login page .

the question is : this test is only for / route , is there any way to test the rest of routes without typing theme all ? someting like $this->get('/*') ?

    public function test_if_user_is_not_logged_must_redirect_to_login_page(){
        $this->get('/')
            ->assertStatus(302);
    }

0 likes
5 replies
jove's avatar

If you use the built in auth middleware isn't it enough to view the routes and see if they have auth?

tykus's avatar
tykus
Best Answer
Level 104

You could instead get the RouteCollection and iterate over each Route registered in the application, checking that the auth middleware has been applied to each.

$routes = app('router')->getRoutes()->getRoutes();

foreach ($routes as $route) {
    $this->assertTrue(
        in_array('auth', $route->gatherMiddleware()), 
        "Failed because {$route->uri()} is not protected by auth middleware"
);
})
alanholmes's avatar

@mostafalaravel

You could look to see how Illuminate\Foundation\Console\RouteListCommand gets a list of all available routes, and see if there is a way to get an array of them to loop through.

From there you would have to manually remove the login/register routes, as they are not meant to redirect you to login.

But you would also have to handle any routes that have params (eg /posts/{id})

bugsysha's avatar

If you put too much logic in your tests they might have a bug and pass when they should fail so it is better to put all those routes manually.

Please or to participate in this conversation.