我正在尝试运行一个测试,其中多个用户正在执行操作。 ActingAs() 函数中要么存在错误,要么我完全错过了一些琐碎的事情。这是场景。我有一个社交媒体网站。我想以一个用户身份登录,执行一项操作(关注另一个用户),然后以另一个用户身份登录并提交帖子。传递到 actAs 函数的第一个用户在所有后续操作中都会持续存在,即使我为第二个用户显式调用 actAs,或者甚至使用我的注销路由尝试注销第一个用户也是如此。这是代码:
//Create the user that will make the post
$user = User::factory()->subscriber()->active()->create();
//Create the user that will follow the first user
$follower = User::factory()->subscriber()->active()->create();
//Login as the 'follower' and perform the action to follow the first user
$this->actingAs($follower)->post('/ajax/follow/User/'.$user->id);
//Now, try to login as the first user and make the post
$request = ['id' => 1,'body' => 'I have a body'];
$response = $this->actingAs($user)->post('/posts/add',$request);
上面失败了,因为即使我在最后一行调用actingAs($user),当我数据转储授权用户时,我发现我仍然以$follower身份登录,即使我专门尝试使以 $user 身份发帖。我尝试过将手动 Auth::logout() 函数内联,我尝试过在充当 $follower 时点击注销路线,以及其他一些事情。无论如何,您扮演的第一个用户似乎成为您在单次测试中可以扮演的唯一用户。
有人有这方面的经验以及如何解决这个问题吗?预先感谢。
我遇到了同样的问题,我这样做了:
$this->app->get('auth')->forgetGuards();
在我的请求之间
所以你的代码应该是这样的:
//Create the user that will make the post
$user = User::factory()->subscriber()->active()->create();
//Create the user that will follow the first user
$follower = User::factory()->subscriber()->active()->create();
//Login as the 'follower' and perform the action to follow the first user
$this->actingAs($follower)->post('/ajax/follow/User/'.$user->id);
$this->app->get('auth')->forgetGuards();
//Now, try to login as the first user and make the post
$request = ['id' => 1,'body' => 'I have a body'];
$response = $this->actingAs($user)->post('/posts/add',$request);
在 Laravel 9 中
$this->actingAs($follower)->post('/ajax/follow/User/'.$user->id);
Auth::forgetGuards();
Auth::shouldUse('web');
$request = ['id' =>1,'body' => 'I have a body'];
$response = $this->actingAs($user)->post('/posts/add',$request);