[英]Test Redirection with RSpec and Capybara (Rails)
我剛剛了解到 RSpec 和 Cabybara 有多么酷,現在正在努力學習編寫實際測試。
我正在嘗試檢查單擊鏈接后是否重定向到特定頁面。 下面是場景
1) I have a page /projects/list - I have an anchor with html "Back" and it links to /projects/show Below is the test i wrote in rspec describe "Sample" do describe "GET /projects/list" do it "sample test" do visit "/projects/list" click_link "Back" assert_redirected_to "/projects/show" end end end
測試失敗並顯示如下失敗消息
Failure/Error: assert_redirected_to "/projects/show" ArgumentError: @request must be an ActionDispatch::Request
請建議我應該如何測試重定向以及我做錯了什么?
試試current_path.should == "/projects/show"
Capybara 還為完全限定的 URL 實現了current_url
方法。
文檔中的更多信息。
編輯
Capybara 現在有一個名為 have_current_path 的 RSpec 匹配器,您可以像這樣使用它: expect(page).to have_current_path(some_other_page_path)
(感謝@bjliu)
我不確定這是否是您所需要的,但在我的測試中我更喜歡這種方法:
...
subject { page }
...
before do
visit some_path_path
# do anything else you need to be redirected
end
it "should redirect to some other page" do
expect(page.current_path).to eq some_other_page_path
end
從設計維基:
在 Rails 中,當機架應用程序重定向時(就像 Warden/Devise 將您重定向到登錄頁面),集成會話未正確更新響應。 因此,助手 assert_redirected_to 將不起作用。
此頁面也有相同的信息: Rspec make sure we ended up at correct path
因此,您需要測試您現在是否在那個 URL 上,而不是測試您是否被重定向到它。
您需要使用路線,例如:
assert_redirected_to projects_path
而不是
assert_redirected_to "/projects/show"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.