Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining Session with Capybara and Rails 3

I have two capybara tests, the first of which signs in a user, and the second which is intended to test functions only available to a logged in user.

However, I am not able to get the second test working as the session is not being maintained across tests (as, apparently, it should be).

require 'integration_test_helper'

class SignupTest < ActionController::IntegrationTest

  test 'sign up' do  
    visit '/'
    click_link 'Sign Up!'
    fill_in 'Email', :with => '[email protected]'
    click_button 'Sign up'
    assert page.has_content?("Password can't be blank")
    fill_in 'Email', :with => '[email protected]'
    fill_in 'Password', :with => 'password'
    fill_in 'Password confirmation', :with => 'password'
    click_button 'Sign up'
    assert page.has_content?("You have signed up successfully.")
  end

  test 'create a product' do
    visit '/admin'
    save_and_open_page
  end

end

The page generated by the save_and_open_page call is the global login screen, not the admin homepage as I would expect (the signup logs you in). What am I doing wrong here?

like image 957
Neil Middleton Avatar asked Jan 19 '11 17:01

Neil Middleton


2 Answers

The reason this is happening is that tests are transactional, so you lose your state between tests. To get around this you need to replicate the login functionality in a function, and then call it again:

def login
  visit '/'
  fill_in 'Email', :with => '[email protected]'
  fill_in 'Password', :with => 'password'
  fill_in 'Password confirmation', :with => 'password'
  click_button 'Sign up'
end

test 'sign up' do
 ...
 login
 assert page.has_content?("You have signed up successfully.")
end

test 'create a product' do
  login
  visit '/admin'
  save_and_open_page
end
like image 193
Pan Thomakos Avatar answered Nov 01 '22 19:11

Pan Thomakos


Each test is run in a clean environment. If you wish to do common setup and teardown tasks, define setup and teardown methods as described in the Rails guides.

like image 3
Andy Lindeman Avatar answered Nov 01 '22 19:11

Andy Lindeman