Proper way to wait for a second page to load with Capybara when the first has the same field as the second

Alex picture Alex · Jan 23, 2014 · Viewed 26.4k times · Source

I'm having a problem with a spec that visits two forms with the same field ("Email") on both forms. If I don't manually sleep, Capybara seems to be finding the "Email" field from the first visit in the second portion of the test.

# visit the first form and fill out a subscription
visit new_front_form_subscription_path(@web_form_1.id)
fill_in "Email", with: "[email protected]"
fill_in "Field 1", with: "my first data"
click_button "Subscribe"

# visit the second form and fill out a subscription
visit new_front_form_subscription_path(@web_form_2.id)
sleep 1
fill_in "Email", with: "[email protected]"
fill_in "Field 2", with: "my second data"
click_button "Subscribe"

With the sleep in there, the spec passes with flying colors. Without the sleep, the second form submission gets a validation error -- blaming a blank "Email" value.

Is there a proper way to handle this? I dislike introducing manual sleeps into the specs.

Answer

Andrei Botalov picture Andrei Botalov · Jan 24, 2014

Here are a couple of ways using which you can solve it:

  1. Use another locator that is present only at the second page to select "Email" field:

    find('#second_page #email').set('[email protected]')
    
  2. Write a statement that will wait for a second page to be loaded instead of sleep:

    visit new_front_form_subscription_path(@web_form_2.id)
    expect(page).to have_css('locator_present_only_at_second_page')
    fill_in "Email", with: "[email protected]"