如果电子邮件未经验证,如何对用户重定向到登录页面进行单元测试



我正在尝试为我的代码编写一些单元测试,我只是在学习如何编写测试,我是Laravel的新手。基本上,我有一个简单的项目,用户应该在其中注册,验证他们的电子邮件后,他们会被重定向到登录页。为了避免一些无限的重定向和错误,我添加了几行代码,防止用户在验证电子邮件之前将自己重定向到登录页。这就是我在控制器文件中的内容:

public function index(): View|RedirectResponse
{
if (auth()->user()->email_verified_at)
{
return view('landing.country', [
'countries'  => Countries::all(),
]);
}
auth()->logout();
return redirect(route('home'));
}

因此,如果用户没有验证他的电子邮件,如果他试图查看只有经过身份验证的用户才能访问的刀片,我会将他注销并重定向到登录页面。尽管写这篇文章很简单,但我很难想出一个合适的方法来测试它。我应该如何测试这个特定的注销部分?我必须测试用户是否试图输入auth-only blade,并检查他是否被注销并重定向到输入页面?任何帮助都将不胜感激,目前我一直在我的测试单元中尝试这样的东西:

public function test_if_user_is_logged_out()
{
User::factory()->create();
$user = User::first();
Auth::logout();
$response = $this->actingAs($user)->get(route('landing.worldwide'));
$response->assertRedirect(route('home'));
}

但显然它不起作用。我将永远感谢任何建议和帮助!

您可以将测试更新为以下内容:

public function test_an_unverified_user_is_logged_out_and_redirected()
{
$user = User::factory()->unverified()->create();
$this->actingAs($user)
->get(route('landing.worldwide'))
->assertRedirect(route('home'));
$this->assertGuest();
}

unverified()是Laravel的新安装中包含的一种方法。如果您的UserFactory中没有unverified(),您可以简单地将用户创建调用更改为:

$user = User::factory()->create([
'email_verified_at' => null,
]);

最新更新