功能测试行为影响所有警卫?



我的应用程序中有两个不同的用户对象,一个AppUser,一个AppAdmin。对于两者,我都有不同的身份验证保护。

我的默认防护装置是模型AppUserweb防护装置,我还有一个用于模型AppAdminadmin防护装置。

例如,此代码

$admin = factory(AppAdmin::class)->make();
Auth::guard('admin')->login($admin);
dd([Auth::check(), Auth::guard('admin')->check()]);

返回

[假,真]

不出所料。

但是,在我的功能测试中,我正在这样做:

$admin = factory(AppAdmin::class)->make();
$response = $this->actingAs($admin, 'admin')
->get('/admin');
dd([Auth::check(), Auth::guard('admin')->check()]);

由于某种原因返回

[真,真]

这会导致所有类型的错误(例如,我有一个针对普通用户的日志中间件,并且尝试将管理员存储为普通用户会抛出foreign_key异常等(。

为什么actingAs启用两个警卫?是 Laravel 5.6 中的错误还是我做错了什么?

当你调用actingAs方法时,Laravel将默认保护更改为内部admin(在本例中(。

请使用下面的代码

$defaultGuard = config('auth.defaults.guard');
$admin = factory(AppAdmin::class)->make();
$this->actingAs($admin, 'admin');
Auth::shouldUse($defaultGuard);
$response = $this->get('/admin');
dd([Auth::check(), Auth::guard('admin')->check()]);

还可以提取TestCase类中actingAsAdmin的方法,以便可以重用该函数。

public function actingAsAdmin($admin) {
$defaultGuard = config('auth.defaults.guard');
$this->actingAs($admin, 'admin');
Auth::shouldUse($defaultGuard);
return $this;
}

并像下面这样调用此函数。

$admin = factory(AppAdmin::class)->make();
$response = $this->actingAsAdmin($admin)->get('/admin');
dd([Auth::check(), Auth::guard('admin')->check()]);

相关内容

最新更新