使用RSpec和Capybara(Rails)测试重定向

39

我刚刚学习了RSPEC和Capybara,现在正在研究如何编写实际测试。

我尝试检查是否点击链接后会重定向到特定页面。以下是场景:

1)我有一个页面 /projects/list
        - 我有一个带有html“Back”的锚点,它链接到 /projects/show
以下是我在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

请给我建议,告诉我应该如何测试重定向以及我错在哪里?

4个回答

83

尝试使用 current_path.should == "/projects/show"

Capybara 还实现了一个current_url方法,用于返回完整的 URL。

更多信息请参见文档

编辑

Capybara 现在有一个名为 have_current_path 的 RSpec 匹配器,可以像这样使用:expect(page).to have_current_path(some_other_page_path) (谢谢 @bjliu)


3
使用projects_path可能更好?顺便使用expect符号。 - mswieboda
1
Capybara现在有一个RSpec匹配器叫做have_current_path,您可以像这样使用它:expect(page).to have_current_path(some_other_page_path) - bjliu

12

我不确定这是否是您需要的,但在我的测试中,我更喜欢这种方法:

...
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

1
page.current_path 是不必要的,因为你已经将 page 声明为主题,所以可以直接使用 current_path - mitra

5

来自Devise wiki:

Rails中,当一个Rack应用程序重定向(就像Warden/Devise将您重定向到登录页面一样),集成会话没有正确更新响应。因此,帮助器assert_redirected_to将无法工作。

同样的信息也在这个页面上:Rspec确保我们到达了正确的路径

因此,您需要测试您现在正在使用该URL,而不是测试您是否被重定向到它。


-3
你需要使用路由,类似这样:
assert_redirected_to projects_path

而不是

assert_redirected_to "/projects/show"

当我使用像assert_redirected_to projects_path这样的代码时,它会显示类似于undefined local variable or method 'projects_path' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x98b1c04>的错误信息。 - balanv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接