Joined April 2014
·

Erran Carey

Software Development Engineer, Test at ThreatAgent
·
Austin, TX
·
·

Posted to Wait for ajax with capybara 2.0 over 1 year ago

I found this through thoughbot's blog. Here are some minor changes I made (from their version). In the application I'm testing the AJAX requests are potentially long. I've added the ability to set a custom wait time AND to ensure that jQuery is defined before calling jQuery.active

# @see http://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara Automatically wait for AJAX with Capybara
def finished_all_ajax_requests?
  return_value = page.evaluate_script <<-SCRIPT.strip.gsub(/\s+/,' ')
    (function () {
      if (typeof jQuery != 'undefined') {
        return jQuery.active;
      }
      else {
        console.log("Failed on the page: " + document.URL);
        console.error("An error occurred when checking for `jQuery.active`.");
      }
    })()
  SCRIPT
  return_value and return_value.zero?
end

# @see http://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara Automatically wait for AJAX with Capybara
def wait_for_ajax(task: 'Waiting for AJAX', wait_time: nil)
  DebugHelpers.time_execution(task) do
    wait_time ||= Capybara.default_wait_time

    Timeout.timeout(wait_time) do
      loop until finished_all_ajax_requests?
    end
  end
end
Achievements
99 Karma
0 Total ProTip Views