Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing multi Auth in Laravel

In my app, I use the Multi Authentication. (I used this link)

It works, and I can log as a user -> I am redirected to "/home"

as an admin, when I log in, I am redirected to "/admin_home"

when connected, admin can't access to "/home", he is redirected to another page

But when I write this test :

class AdminTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        Artisan::call('migrate');
        Artisan::call('db:seed');
    }

    public function tearDown()
    {
        Artisan::call('migrate:reset');
        parent::tearDown();
    }


    public function testCannotAccessUserSpace()
    {
        $admin = Admin::find(1);

        $response = $this->actingAs($admin, 'admin')
            ->get('/home');

        $response->assertStatus(200);
    }

}

I have a success response but I know the admin cannot access "home" space

What's wrong in my test ?

like image 442
pop_up Avatar asked May 19 '26 04:05

pop_up


1 Answers

Okay, so after some struggle I've finally found the issue.

I implemented the multi-auth using the same link.

The problem is in your HomeController.php not in the AdminTest.

Just like you have specified the authentication guard in your AdminController.php constructor, you have to do it in HomeController.php also.

As you know (assuming you've followed the link) for AdminController.php it is like this:

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

In here we've specified in the constructor that we need to authenticate against the admin guard but in HomeController we didn't.

HomeController.php Before:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

HomeController.php After:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:web');
    }

Solution is

$this->middleware('auth');

changes to

$this->middleware('auth:web');

Now, if you run the test it will show the following error:

PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

F..                                                                 3 / 3 (100%)

Time: 124 ms, Memory: 10.00MB

There was 1 failure:

1) Tests\Feature\AdminTest::testCannotAccessUserSpace
Expected status code 200 but received 302.
Failed asserting that false is true.
like image 57
Tahir Raza Avatar answered May 22 '26 04:05

Tahir Raza