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 => 'bob@wagonlabs.com'
click_button 'Sign up'
assert page.has_content?("Password 开发者_开发百科can't be blank")
fill_in 'Email', :with => 'bob@wagonlabs.com'
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?
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 => 'bob@wagonlabs.com' 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
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.
精彩评论