Friday, October 11, 2013

Checking Jquery Ajax requests from Capybara

I was working in a particular feature today. I wanted to test an autocomplete input box that makes its requests via Ajax. Something very common.

I wanted to test that the requests were being done to the right URL in a black box kind of way using the cucumber features.

This is what I did:

  • First added a new visit method visit_tracking_ajax to my Cucumber environment with the following content

    module CucumberGlobals
     def visit_tracking_ajax(url)
      visit(url)
      page.execute_script("$(document).ajaxSuccess(function(a,b,c){console.log(this);window._latest_ajax_url_called = c.url;})")
     end
    end
    
    World(CucumberGlobals)
    

This executes a Javascript Jquery script in the page that will listen to every Ajax request being made (through Jquery) and set a variable on window with the URL called in that request.

  • Then from my step definition I did something like:

    page.latest_ajax_url.should == 'http://www.xx.xxx'
    
  • Having also added the following method to the Capybara session:

    module CustomMethods
     def latest_ajax_url
       evaluate_script("window._latest_ajax_url_called")
     end
    end
    
    module Capybara
      class Session
        include CustomMethods
      end
    end
    

That's it, now I was checking the last ajax url being called. This is fragile code, but it worked fine for my current use case.

No comments: