Skip to content

Instantly share code, notes, and snippets.

@jlindsey
Created June 3, 2010 16:47
Show Gist options
  • Save jlindsey/424127 to your computer and use it in GitHub Desktop.
Save jlindsey/424127 to your computer and use it in GitHub Desktop.
Using Cucumber/Capybara/Culerity, a step to wait until all AJAX calls are complete.
// this allows culerity to wait until all ajax requests have finished
jQuery(function($) {
var original_ajax = $.ajax;
var count_down = function(callback) {
return function() {
try {
if(callback) {
callback.apply(this, arguments);
};
} catch(e) {
window.running_ajax_calls -= 1;
throw(e);
}
window.running_ajax_calls -= 1;
};
};
window.running_ajax_calls = 0;
var ajax_with_count = function(options) {
if(options.async == false) {
return(original_ajax(options));
} else {
window.running_ajax_calls += 1;
options.success = count_down(options.success);
options.error = count_down(options.error);
return original_ajax(options);
}
};
$.ajax = ajax_with_count;
});
<%
# In the <head> of your layout template
if RAILS_ENV == 'test' or RAILS_ENV == 'cucumber' or RAILS_ENV == 'culerity'
puts javascript_include_tag('culerity')
end
%>
When /^I wait for the AJAX call to finish$/ do
keep_looping = true
while keep_looping do
# TODO: Test this. It might be more efficient by sleeping for < 1 second.
sleep 1
begin
count = page.evaluate_script('window.running_ajax_calls').to_i
keep_looping = false if count == 0
rescue => e
if e.message.include? 'HTMLunitCorejsJavascript::Undefined'
raise "For 'I wait for the AJAX call to finish' to work, please include culerity.js after including jQuery."
else
raise e
end
end
end
end
@supairish
Copy link

Good stuff, just the step I was looking for. Thanks

I should mention there is a small typo on line 10 of web_steps.rb, missing an opening parenthesis or need to delete the closing one :-)

@jlindsey
Copy link
Author

Not a problem.

Fixed the typo in web_steps.rb, thanks for pointing it out :)

@mustmodify
Copy link

+1 thanks

@ezotrank
Copy link

web_steps.rb:9 forgot first (
if (e.message.include? 'HTMLunitCorejsJavascript::Undefined')

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