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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With