Skip to content

Instantly share code, notes, and snippets.

@qcam
Created May 3, 2014 00:41
Show Gist options
  • Save qcam/11489603 to your computer and use it in GitHub Desktop.
Save qcam/11489603 to your computer and use it in GitHub Desktop.
Wait for AJAX in Capybara

Wait for AJAX Capybara

Add wait_for_ajax to your helper

def wait_for_ajax
  Timeout.timeout(Capybara.default_wait_time) do
    loop do
      active = page.evaluate_script('jQuery.active')
      break if active == 0
    end
  end
end

In your Capybara test case

click_on "Load more"
wait_for_ajax
expect(page).to have_content "New Product"
@miklblitz
Copy link

thank you very much

@robmadden
Copy link

Capybara 2.16.1: Capybara.default_wait_time should be default_max_wait_time

@kirill3333
Copy link

what if we use axios or fetch ?

@aenain
Copy link

aenain commented Jan 31, 2020

@kirill3333 for axios interceptors can be used to set count on a global variable

# spec/support/helpers/capybara_wait_for_ajax.rb
module CapybaraWaitForAjax
  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('window.pendingRequestCount').zero?
  end
end

RSpec.configure do |config|
  config.include CapybaraWaitForAjax, type: :feature
end
// app/javascript/src/api/install_ajax_tracker.js
import axios from 'axios'

let pendingRequestCount = 0

axios.interceptors.request.use(config => {
  pendingRequestCount++
  return config
}, Promise.reject)

axios.interceptors.response.use(
  response => {
    pendingRequestCount--
    return response
  },
  error => {
    pendingRequestCount--
    return Promise.reject(error)
  }
)

window.pendingRequestCount = pendingRequestCount

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