mahmoudghalayini's avatar

Test that HTTP error code 401 is returned when user is not authenticated

I want to check if use is authenticated or not.

0 likes
4 replies
wingly's avatar

You can use

    public function testExample()
    {
        $response = $this->get('/');

        $response->assertStatus(401);
    } 
Tray2's avatar

Something like this should work

    /**
     * @test
     */
    public function guests_are_unathorized()
    {
        $response = $this->get('/dashboard');
	$response->assertStatus(401);
    }

In the code below I test my protected routes and check that the guest is redirected to the login page

    public function protectedRoutesProvider()
    {
        return [
          'Artists: a guest is not authorized to visit the create page' => ['get', '/artists/create'],
          'Artists: a guest is not authorized to visit the edit page' => ['get', '/artists/1/edit'],
          'Artists: a guest is not authorized to visit the store page' => ['post', '/artists'],
          'Artists: a guest is not authorized to visit the update page' => ['put', '/artists/1'],
          'Artists: a guest is not authorized to visit the delete page' => ['delete', '/artists/1'],
        ];
    }

    /**
     * @test
     * @dataProvider protectedRoutesProvider
     * @param $method
     * @param $route
     */
    public function guests_are_redirected_to_login($method, $route)
    {
        $response = $this->$method($route);
        $response->assertLocation('/login');
    }
mahmoudghalayini's avatar

@tray2 ran your code and I got this

  1. Tests\Feature\UserTest::test_guests_are_unathorized Expected status code 401 but received 302. Failed asserting that false is true.
Tray2's avatar

302 means a redirect and that is the normal response when you are using the auth middlewre. It redirects to the login page. That is why I do it as in the second example.

Please or to participate in this conversation.