我正在使用提供的幾乎完全開箱即用的注冊流程Laravel 7。當我嘗試通過網絡瀏覽器中的表單提交無效的注冊表單時,我會返回到注冊頁面,其中包含錯誤列表,這正是我期望發生的情況。但是,我正在嘗試為此功能編寫一個單元測試,但由于某種原因,當我在單元測試中發出相同的請求時,我得到了重定向到 root page 的響應/。為什么我的單元測試沒有返回與通過瀏覽器發出相同請求時相同的 HTML 響應?我懷疑這可能是由于請求中缺少發送的 CSRF 令牌,但根據文檔,CSRF 中間件應該在單元測試期間被禁用。運行測試時,CSRF 中間件會自動禁用。這是我的單元測試代碼:public function testPostInvalidRegistration(){ $response = $this->post("/register",[ 'first_name' => $this->faker->name ]); $response->dumpSession(); $response->dump(); $response->dumpHeaders();}這是輸出$response->dump()<!DOCTYPE html>\n<html>\n <head>\n <meta charset="UTF-8" />\n <meta http-equiv="refresh" content="0;url='http://localhost'" />\n\n <title>Redirecting to http://localhost</title>\n </head>\n <body>\n Redirecting to <a href="http://localhost">http://localhost</a>.\n </body>\n</html>我$response->dumpSession()可以看到驗證器已運行并列出了錯誤。
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
這就是 Laravel 的工作方式。當表單驗證失敗時,您將被重定向到之前的位置。由于您的測試中只有一個請求,因此沒有先前的位置。后備方法是重定向到/.
對于您想要的行為,您必須將referer標題設置為注冊表單頁面的路徑。要獲取表單的渲染響應,您必須遵循重定向。
public function testPostInvalidRegistration()
{
$this->followingRedirects();
$response = $this->post(
"/register",
[
'first_name' => $this->faker->name
],
['Referer' => '/registration-form']
);
// Assert stuff
}
- 1 回答
- 0 關注
- 105 瀏覽
添加回答
舉報
0/150
提交
取消