Ajax requests in testing

I have the following scenario:

feature 'locations index page', js: :true do
  scenario "can make a new location" do
    click_link "New Location"
    within("#new_location") do
      fill_in "location_address_1", with: "location 3"
    end
    click_button "Create Location"
    page.should have_content "location 3"
    current_path.should == location_path(Location.last)
  end
end

Using phantomjs 1.9.1 and poltergeist 1.4.0 as capybara’s javascript_driver.

This test intermittently fails with expected to find text "location 3" in ... and if I add in a save_and_open_page it shows the form submitted (button has changed from ‘create’ to ‘creating’) but the ajax response hasn’t returned to insert the new location into the page. This test always passes with a sleep thrown in before the assertion. It sometimes passes without the sleep.

Is there a way to ensure ajax requests have finished before the assertion is run? I was under the impression capybara already did this. I’m using capybara 2.1.0

Have you tried using find?

From the capybara read me:

Note: find will wait for an element to appear on the page, as explained in the Ajax section. If the element does not appear it will raise an error.