Skip to content

Instantly share code, notes, and snippets.

@hugomaiavieira
Last active May 24, 2018 20:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hugomaiavieira/269b0a5f5a8a3e532d8a to your computer and use it in GitHub Desktop.
Save hugomaiavieira/269b0a5f5a8a3e532d8a to your computer and use it in GitHub Desktop.
Wait for ajax on ruby with capybara
# Ajax testing with ruby and capybara
#
# Add this to spec/support
#
# When a link or button starts an ajax request, instead of use Capybara
# click_link, click_button and click_link_or_button methods use click_ajax_link,
# click_ajax_button and click_ajax_link_or_button methods. You can still use
# capybara methods and right after it, call wait_for_ajax method.
#
# This methods will wait until Capybara.default_max_wait_time for the ajax request
# to finish before continue the normal tests flow.
#
require 'timeout'
module WaitForAjax
def wait_for_ajax(&block)
yield if block_given?
Timeout.timeout(Capybara.default_max_wait_time) do
loop do
sleep 0.1
break if finished_all_ajax_requests?
end
end
end
def click_ajax_link(locator, options = {})
click_link(locator, options)
wait_for_ajax
end
def click_ajax_button(locator, options = {})
click_button(locator, options)
wait_for_ajax
end
def click_ajax_link_or_button(locator, options = {})
click_link_or_button(locator, options)
wait_for_ajax
end
def finished_all_ajax_requests?
page.evaluate_script('jQuery.active').zero?
end
end
RSpec.configure do |config|
config.include WaitForAjax
end
@yurifds
Copy link

yurifds commented Jan 12, 2016

atualizar para default_max_wait_time pois o default_wait_time está deprecated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment