Waiting for AJAX with Capybara + Poltergeist
<p>I've seen various implementations of the <code>wait_for_ajax</code> method that makes Capybara wait until all AJAX requests are completed before moving forward. </p>

<p>I've just switched to using Poltergeist as my JavaScript driver and I'm having trouble getting it to wait for the AJAX to complete on a test (see below)</p>

<p>Below is the implementation that was previously working with Selenium - the only thing I modified was the evaluation script -</p>

<ul>
<li>Previous: <code>page.evaluate_script("jQuery.active")</code></li>
<li>Updated: <code>page.evaluate_script("$.active").to_i</code></li>
</ul>

<p>If I insert a <code>sleep</code> statement it passes because it has enough time to finish the AJAX call, so I definitely know that's the issue.</p>

<p>Is there any error in this approach?</p>

<p>Thanks!</p>

<pre><code>it "user can log in", js: true do
  visit root_path
  click_tab("log-in")

  # Fill in form
  fill_in "user[email]", with: "al-horford@hawks.com"
  fill_in "user[password]", with: "sl4mdunkz"

  # Click submit and wait for AJAX
  within("#log-in") { click_button("Log In")) }
  wait_for_ajax

  # Expectations
  expect(current_path).to eq(home_index_path)
end

def wait_for_ajax
  Timeout.timeout(Capybara.default_max_wait_time) do
    loop until finished_all_ajax_requests?
  end
end

def finished_all_ajax_requests?
  request_count = page.evaluate_script("$.active").to_i
  request_count &amp;&amp; request_count.zero?
rescue Timeout::Error
end
</code></pre>