Ruby-on-rails 使用 RSpec 和 Capybara(Rails)测试重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11224290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test Redirection with RSpec and Capybara (Rails)
提问by balanv
I just have learnt how cool RSpec and Cabybara is, and now working around it to learn writing actual test.
我刚刚了解到 RSpec 和 Cabybara 有多酷,现在正在围绕它学习编写实际测试。
I am trying to check if after clicking a link, there is a redirection to a specific page. Below is the scenario
我试图检查单击链接后是否重定向到特定页面。下面是场景
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
The test fails with a failure message like below
测试失败,并显示如下失败消息
Failure/Error: assert_redirected_to "/projects/show"
ArgumentError:
@request must be an ActionDispatch::Request
Please suggest me on how i should test the redirection and what am i doing wrong?
请建议我应该如何测试重定向以及我做错了什么?
回答by zetetic
回答by kovpack
Im not sure that this can be what you need, but in my tests I prefer such approach:
我不确定这是否可以满足您的需求,但在我的测试中,我更喜欢这种方法:
...
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
回答by Jesse Wolgamott
From the Devise wiki:
从设计维基:
In Rails when a rack application redirects (just like Warden/Devise redirects you to the login page), the response is not properly updated by the integration session. As consequence, the helper assert_redirected_to won't work.
在 Rails 中,当机架应用程序重定向时(就像 Warden/Devise 将您重定向到登录页面一样),集成会话不会正确更新响应。因此,助手 assert_redirected_to 将不起作用。
Also this page has the same information: Rspec make sure we ended up at correct path
此页面也有相同的信息:Rspec 确保我们以正确的路径结束
So you'll need to test that you're now on that URL, rather than test that you are being redirected to it.
因此,您需要测试您现在是否在该 URL 上,而不是测试您是否被重定向到该 URL。
回答by Adrian
You need to use the route, something like:
您需要使用路线,例如:
assert_redirected_to projects_path
rather than
而不是
assert_redirected_to "/projects/show"

