php - Laravel 5.4 - integration testing role middleware fails
I'm trying to test some middleware that checks to see if a user hasx
role with Laravel 5.4/PHPUnit. The role functionality works fine in the browser, but I can't seem to get my tests to pass (I get 403's as expected with someone without the required role) with the following code:
public function testSuperAdminRoleRoute()
{
$admin = factory(User::class)->create();
$adminRole = \HttpOz\Roles\Models\Role::whereSlug('super.admin')->first();
$admin->detachAllRoles();
$admin->attachRole($adminRole);
$response = $this->actingAs($admin)
->get('/super-admin-only')
->assertStatus(200);
}
When Idd($admin->roles)
I do indeed see the correct role, but I think I'm missing something maybe a limitation within Laravel/PHPUnit. I have previously tested this sort of functionality in my acceptance tests and had it work.
Any advice is much appreciated!
Answer
Solution:
After talking to the package author (httoz), we believe it's due to a limitation of Laravel's
be()
oractingAs()
methods. We're not really 100% sure as to why, but I believe sessions come into play, and PHPUnit uses an array as session storage, so I'm pushed towards that.I tried to use
$this->disableMiddleware()
, but because I use the$error
bag in my views (and that is set via middleware), my tests 500 because$errors
isn't defined.However, reading this proposed change in Laravel 5.5: https://github.com/laravel/framework/pull/18673
I copied the code from that push:
and set updated my
$this->withoutMiddleware()
calls to this:and I get green again!