Rails - Losing session with Integration Tests and Capybara - CSRF related? Rails - Losing session with Integration Tests and Capybara - CSRF related? ruby-on-rails ruby-on-rails

Rails - Losing session with Integration Tests and Capybara - CSRF related?


I'm new to capybara too and I was having a similar problem.

I was trying to login a user doing something like this:

post user_session_path, :user => {:email => user.email, :password => 'superpassword'}

And that was working ok until I tried to do something with capybara, such as visiting a page and just testing if the user was logged in. This simple test was not passing:

visit root_pathpage.should have_content("logout") #if the user is logged in then the logout link should be present

At first I thought capybara was clearing the sessions but I was wrong. The thing that took me some time to realize is that the driver capybara is using handles its own sessions, so, from the point of view of capybara my user was never logged in. To do so you have to do it like this

page.driver.post user_session_path, :user => {:email => user.email, :password => 'superpassword'}

Not sure if this is your case, but hope that helps.


I was able to fix this error by setting this value to true in config/initializers/test.rb

# Disable request forgery protection in test environmentconfig.action_controller.allow_forgery_protection = true

Beforehand, the CSRF <meta> tags were not printing out to the <head>. After changing this value they finally appear.


The manual way of doing it is very simple:

it "does something after login" do  password = "secretpass"  user = Factory(:user, :password => password)  visit login_path  fill_in "Email", :with => user.email  fill_in "Password", :with => password  click_button "Log in"  visit # somewhere else and do somethingend

You can then break this out into a function in your 'spec_helper.rb':

# at the bottom of 'spec_helper.rb'def make_user_and_login  password = "secretpass"  @user = Factory(:user, :password => password)  visit login_path  fill_in "Email", :with => @user.email  fill_in "Password", :with => password  click_button "Log in"end

and use it in any of your tests (probably request specs):

it "does something after login" do  make_user_and_login  # now test something that requires a logged in user  # you have access to the @user instance variableend