简体   繁体   中英

Race condition in Capybara

I think I've met a race condition when I visit some page, fill the form and visit another page after this. Here is full spec.

describe "Dashboard", js: true do
  it 'should be displayed for logged in writer' do
    # sign_in
    visit '/login'
    within(".login-form") do
      fill_in 'login', with: 'existing_user@example.com'
      fill_in 'password', with: 'somepassword'
    end
    click_button 'LOGIN'

    # test itself
    visit '/dashboard'
    expect(page).to have_content 'Welcome back!'

    # sign_out
    visit '/dashboard'
    find('span', text: 'Logout').click
  end
end

This test is failing even with default_max_wait_time set to 15 . However it works with sleep 1 :

# test itself
sleep 1
visit '/dashboard'
expect(page).to have_content 'Welcome back!'

Is there a better way to avoid this race condition?

After clicking your 'LOGIN' button you need to wait for a change that shows the login has completed. This is because things happen asynchronously in JS capable browsers, all click_button does is click the button, it doesn't wait for any effects clicking the button does. So you want something like

click_button 'LOGIN'
expect(page).to have_text('You are logged in')  # whatever text makes sense on your site
visit '/dashboard'
...

Also the test you're showing has logout - but doesn't actually confirm the user is logged out - so it's a useless part of the test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM