Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Redirection with RSpec and Capybara (Rails)

I just have learnt how cool RSpec and Cabybara is, and now working around it to learn writing actual test.

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?

like image 422
balanv Avatar asked Jun 27 '12 10:06

balanv


3 Answers

Try current_path.should == "/projects/show"

Capybara also implements a current_url method for the fully qualified URL.

More info in the docs.

EDIT

Capybara now has a RSpec matcher called have_current_path, which you can use like: expect(page).to have_current_path(some_other_page_path) (thanks @bjliu)

like image 142
zetetic Avatar answered Nov 05 '22 00:11

zetetic


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
like image 42
kovpack Avatar answered Nov 05 '22 01:11

kovpack


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.

Also this page has the same information: Rspec make sure we ended up at correct path

So you'll need to test that you're now on that URL, rather than test that you are being redirected to it.

like image 5
Jesse Wolgamott Avatar answered Nov 05 '22 01:11

Jesse Wolgamott