Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I re-use Capybara sessions between tests?

I want to keep on using the same session and by that I mean Rails' session between various Test::Unit integration tests that use Capybara. The Capybara::Session object is the same in all the tests as it is re-used, but when I access another page in another test, I'm immediately logged out.

Digging in I found that capybara_session.driver.browser.manage.all_cookies is cleared between one test and the next.

Any ideas how? or why? or how to avoid it?

Trying to work-around that, I saved the cookie in a class variable and re-added later by running:

capybara_session.driver.browser.manage.add_cookie(@@cookie)

and it seems to work, the cookie is there, but when there's a request, the cookie gets replaced for another one, so it had no effect.

Is there any other way of achieving this?

like image 965
pupeno Avatar asked Sep 26 '12 15:09

pupeno


People also ask

What is Rspec capybara?

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language. Capybara.


2 Answers

Add the following after your capybara code that interacts with the page:

Capybara.current_session.instance_variable_set(:@touched, false)

or

page.instance_variable_set(:@touched, false)

If that doesn't work, these might help:

https://github.com/railsware/rack_session_access

http://collectiveidea.com/blog/archives/2012/01/05/capybara-cucumber-and-how-the-cookie-crumbles/

like image 173
Erik Peterson Avatar answered Oct 22 '22 12:10

Erik Peterson


If what you are doing is trying to string together individual examples into a story (cucumber style, but without cucumber), you can use a gem called rspec-steps to accomplish this. For example, normally this won't work:

describe "logging in" do
  it "when I visit the sign-in page" do 
    visit "/login"
  end
  it "and I fill in my registration info and click submit" do
    fill_in :username, :with => 'Foo'
    fill_in :password, :with => 'foobar'
    click_on "Submit"
  end
  it "should show a successful login" do
    page.should have_content("Successfully logged in")
  end
end

Because rspec rolls back all of its instance variables, sessions, cookies, etc.

If you install rspec-steps (note: currently not compatible with rspec newer than 2.9), you can replace 'describe' with 'steps' and Rspec and capybara will preserve state between the examples, allowing you to build a longer story, e.g.:

steps "logging in" do
  it "when I visit the sign-in page" #... etc.
  it "and I fill in" # ... etc.
  it "should show a successful" # ... etc.
end
like image 32
Evan Avatar answered Oct 22 '22 11:10

Evan