我使用来自spatie的permission package。
它正在工作但我的测试仍然失败。
我的测试看起来像这样:
/** @test */
public function a_user_with_right_permission_can_update_company_profile()
{
$role = create(Role::class, ['name' => 'super-admin']);
$permission = create(Permission::class, ['name' => 'bewerk-bedrijf-instellingen']);
$role->givePermissionTo($permission->name);
$user = create(User::class)->assignRole($role->name);
$user = $user->fresh();
$this->signIn($user);
$settings = [
'name' => 'Company',
'email' => 'info@example.com',
'phone' => '0623844932',
'website' => 'http://www.example.com',
'description' => 'A short description',
];
$this->patch('/instellingen/bedrijf/profiel', $settings)
->assertSessionHas('status', 'Bedrijfsprofiel geupdatet!');
$this->assertDatabaseHas('settings', $settings);
}
我收到此错误消息:
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'Bedrijfsprofiel geupdatet!'
+'Niet geautoriseerd!'
所以它告诉我,我没有被授权这样做!但我得到了正确的许可。因为这是该控制器中的中间件:
public function __construct()
{
$this->middleware('permission:bewerk-bedrijf-instellingen');
}
当我删除中间件时,测试工作正常。这可能是一个缓存问题?
- 编辑 -
/** @test */
public function a_user_with_right_permission_can_update_company_profile()
{
$permission = Permission::create([
'name' => 'bewerk-bedrijf-instellingen'
]);
$role = Role::create([
'name' => 'super-admin'
]);
$role->givePermissionTo($permission->name);
$user = User::create([
'name' => 'First',
'last_name' => 'Last',
'email' => 'info@example.com',
'password' => 'secret',
'password_confirmation' => 'secret',
'function' => 'Developer',
]);
$user = $user->fresh();
$this->signIn($user);
$settings = [
'name' => 'Company',
'email' => 'info@example
.com',
'phone' => '0623844932',
'website' => 'http://www.example.com',
'description' => 'A short description',
];
$this->patch('/instellingen/bedrijf/profiel', $settings)
->assertSessionHas('status', 'Bedrijfsprofiel geupdatet!');
$this->assertDatabaseHas('settings', $settings);
}
中间件
public function handle($request, Closure $next, $permission)
{
if (Auth::guest()) {
return redirect('/');
}
if (!$request->user()->hasPermissionTo($permission)) {
return back()
->with('status', 'Niet geautoriseerd!');
}
return $next($request);
}
当我在中间件中dd($request->user()->hasPermissionTo($permission));
时,我收到了错误信息。当我dd($request->user()->roles()->pluck('name'));
收到super-admin
时。