【发布时间】:2016-09-26 14:06:37
【问题描述】:
Laravel 5.2 版
在我的项目中,role_id = 4 的用户具有管理员角色,可以管理用户。
我在 AuthServiceProvider 中定义了以下能力:
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
$gate->define('can-manage-users', function ($user)
{
return $user->role_id == 4;
});
}
我在UserController的__construct方法中使用了这个能力,如下:
public function __construct()
{
$this->authorize('can-manage-users');
}
在 ExampleTest 中,我创建了两个测试来检查定义的授权是否有效。
对于 role_id = 4 的管理员用户的第一个测试。此测试通过。
public function testAdminCanManageUsers()
{
$user = Auth::loginUsingId(1);
$this->actingAs($user)
->visit('users')
->assertResponseOk();
}
第二个测试是针对另一个没有 role_id = 4 的用户。我尝试过响应状态为 401 和 403。但测试失败:
public function testNonAdminCannotManageUsers()
{
$user = Auth::loginUsingId(4);
$this->actingAs($user)
->visit('users')
->assertResponseStatus(403);
}
失败信息的前几行如下:
对 [http://localhost/users] 的请求失败。收到状态码 [403]。
C:\wamp\www\laravel\blog\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:196 C:\wamp\www\laravel\blog\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:80 C:\wamp\www\laravel\blog\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithPages.php:61 C:\wamp\www\laravel\blog\tests\ExampleTest.php:33
由异常'Illuminate\Auth\Access\AuthorizationException'引起 带有消息“此操作未经授权。”在 C:\wamp\www\laravel\blog\vendor\laravel\framework\src\Illuminate\Auth\Access\HandlesAuthorization.php:28
我也尝试过如下使用'see'方法:
public function testNonAdminCannotManageUsers()
{
$user = Auth::loginUsingId(4);
$this->actingAs($user)
->visit('users')
->see('This action is unauthorized.');
}
但它也失败了。我究竟做错了什么?我怎样才能使测试通过?
【问题讨论】:
-
这个问题有什么进展吗?
标签: php unit-testing laravel phpunit laravel-5.2