TIL : Capybara and AJAX

Helper:

# spec/support/wait_for_ajax.rb 
module WaitForAjax 
  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?
    page.evaluate_script('jQuery.active').zero? 
  end 
end 

RSpec.configure do |config| 
  config.include WaitForAjax, type: :feature 
end

Usage:

click_link "Check validity"
wait_for_ajax 
click_link "Create" # if this is a button that depends on "Check validity" to be disabled/enabled, it will have the correct status before the test is executed

Source: https://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara

Leave a Reply