Search code examples
ruby-on-railsrspecwebkitcapybaracapybara-webkit

rspec + webkit is losing session/cookie after first request


using rspec with the default driver is working fine and all tests are passed.

changing driver: :webkit will have a bad side-effect.

  1. step: the user is logged in
  2. step: visiting root_path with a session (current_user)
  3. step: visiting root_path without a session (current_user = nil)

so either after the first visit root_path or before the second, the session is killed or whatever - we can't get the user to stay logged in.

test looks like this

scenario 'something', driver: :webkit do
  user = FactoryGirl.create :user
  login_as(user)
  visit root_path
  visit root_path
end

is this a known bug? are there any workarounds or are we missing something ?


as requested:

 def login_as(user)
    visit root_path
    click_on "Login"
    fill_in "user[login]", with: user.username
    fill_in "user[password]", with: user.password
    click_on "Sign in"
  end

Solution

  • The default driver runs everything synchronously --- drivers that use real browsers and support javascript do not necessarily do things synchronously - so it's possible in drivers other than rack-test for click_on 'Sign in' to return immediately. Therefore if you're not checking for content that would be seen on success the next visit root_path can get executed immediately and cancel the submission of the login form. To fix that add something like

    expect(page).to have_content('You are now logged in') # whatever text is shown on a successful login
    

    as the last line of your login_as method. This is not normally an issue for most people, because after logging in the next step is usually to click on something on the page, which will make Capybara wait for that item to appear thereby waiting for the login to complete.

    If that is not what is happening here then the only place (given your sample code) that can be logging the user out is your own app