Maintaining Session with Capybara and Rails 3

对着背影说爱祢 提交于 2019-12-06 03:06:41

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4738859/maintaining-session-with-capybara-and-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!