A Solution to AJAX errors with Capybara against a jQuery site

Ajax has long been a pain for browser-based test automation; it is often the main culprit when looking for the reasons behind some flakey tests. The normal scenario is this:

  1. Your test clicks a button which fires off an ajax transaction
  2. While the browser is talking to the server, the next line in your test executes
  3. Result? A failing test and a nice big irrelevant stack trace
  4. Frustration
  5. Reduction in self-esteem
  6. Spend a while trying to pin down and make allowances in the code for the problem

Well, if you’re using capybara to test a site that’s using jQuery, the following may help – it’s a method called wait_for_ajax that blocks until there are no active connections between the browser and the server. Basically, it *should* sort out any ajax-related problems. No guarantees though. But it does work for me…

To use it, call wait_for_ajax just after the line of code that kicks off the ajax transaction.

The method is in a module called AjaxWaiter that gets included into ‘World‘ (this example uses cucumber, ‘World‘ is not relevant if you’re not using cucumber). Anything added to World can be used in any of your steps. To use the above it in its current form, stick it in your cucumber project’s env.rb file. Here’s an example of wait_for_ajax‘s use in cucumber:

Well, I hope that helps. I know it’s improved my life…

One thought on “A Solution to AJAX errors with Capybara against a jQuery site

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>