Placid's avatar

Test Unauthorized Access using PHPUnit

I am trying to test unauthorized access in Laravel 5.2 using PHPUnit.

AuthServiceProvider.php:

        $gate->define('foo', function ($user)
        {
            return $user->email == '[email protected]';
        });

routes.php:

Route::get('foo', 'PagesController@foo');

PagesController.php:

    public function foo()
    {
        $this->authorize('foo');
        return "Hello foo";
    }

Its working properly in browser. The user [email protected] (user with id 1) can access 'localhost/foo' url. Others can't.

Test:

    /**
     * @test
     */
    public function it_allows_authorized_user()
    {
        $user = Auth::loginUsingId(1);

        $this->actingAs($user)
        ->visit('foo')
        ->assertResponseOk();
    }

    /**
     * @test
     */
    public function it_blocks_unauthorized_access()
    {
        $user = Auth::loginUsingId(2);

        $this->actingAs($user)
        ->visit('foo')
        ->assertResponseStatus(403);
    }

The second test is failing. What am I doing wrong? How to test this?

0 likes
1 reply
tomopongrac's avatar
Level 51

Try with this

$this->get(route($route))
            ->assertResponseStatus(403);

visit expect 200

1 like

Please or to participate in this conversation.