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

时间:2012-06-27 10:36:04

标签: ruby-on-rails rspec capybara

我刚学会了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

请建议我如何测试重定向以及我做错了什么?

4 个答案:

答案 0 :(得分:69)

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

Capybara还为完全限定的URL实现了current_url方法。

docs中的更多信息。

答案 1 :(得分:11)

我不确定这可能是你需要的,但在我的测试中我更喜欢这样的方法:

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

答案 2 :(得分:4)

来自Devise wiki

  

在Rails中,当机架应用程序重定向时(就像Warden / Devise将您重定向到登录页面一样),集成会话未正确更新响应。因此,助手assert_redirected_to将无效。

此页面也有相同的信息:Rspec make sure we ended up at correct path

因此,您需要测试您现在是否在该网址上,而不是测试您是否被重定向到该网址。

答案 3 :(得分:-2)

您需要使用路线,例如:

assert_redirected_to projects_path

而不是

assert_redirected_to "/projects/show"
相关问题