Laravel 5.4 - 集成测试角色中间件失败

Laravel 5.4 - integration testing role middleware fails

我正在尝试测试一些中间件,这些中间件会检查用户是否具有 x 与 Laravel 5.4/PHPUnit 的角色。角色功能在浏览器中运行良好,但我似乎无法使用以下代码通过我的测试(我得到了 403,因为有人没有所需的角色):

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);
}

当我 dd($admin->roles) 时,我确实看到了正确的角色,但我认为我遗漏了一些东西,可能是 Laravel/PHPUnit 中的一个限制。我之前在我的验收测试中测试过这种功能并且它有效。

非常感谢任何建议!

在与软件包作者 (httoz) 交谈后,我们认为这是由于 Laravel 的 be()actingAs() 方法的限制所致。我们并不是真的 100% 确定为什么,但我相信会话会起作用,并且 PHPUnit 使用数组作为会话存储,所以我被推向了这一点。

我尝试使用 $this->disableMiddleware(),但是因为我在我的视图中使用了 $error 包(这是通过中间件设置的),所以我的测试是 500,因为 $errors 不是定义。

但是,阅读 Laravel 5.5 中提议的更改:https://github.com/laravel/framework/pull/18673

我复制了那个推送的代码:

public function withoutMiddleware($middleware = null)
{
    if (is_null($middleware)) {
        $this->app->instance('middleware.disable', true);
        return $this;
    }
    $nullMiddleware = new class {
        public function handle($request, $next)
        {
            return $next($request);
        }
    };
    foreach ((array) $middleware as $abstract) {
        $this->app->instance($abstract, $nullMiddleware);
    }
    return $this;
}

并设置更新了我的 $this->withoutMiddleware() 调用:

$this->withoutMiddleware([
    \HttpOz\Roles\Middleware\VerifyRole::class, 
    \HttpOz\Roles\Middleware\VerifyGroup::class
]);

我又变绿了!