FireWatir and AJAX
Posted 3 days ago
I’ve been working on building some automated testing for a single page, AJAX heavy application. One main view with lots of lightboxes, partial page updates, etc. I wanted to test the application using FireWatir, but ran into what a lot of other people run into: Watir and FireWatir do not wait on AJAX requests to finish before continuing execution. So, if you wrote the following code:
$ff.goto("www.yourajaxyapp.com")
$ff.elements_by_xpath("//div[@id='test']").first.click
$ff.elements_by_xpath("//div[@id='test2']").first.click
If test2 is created by clicking on div#test’s anchor, test2 will not exist and FireWatir will explode and exit. I wrote this really simple block that helps make these kinds of things happen less:
def ajax_handler(xpath, &block)
captured_block = $ff.elements_by_xpath(xpath)
until $ff.elements_by_xpath(xpath) != captured_block
sleep 1
end
yield
end
def after_tab_updates(&block)
ajax_handler("//tr[@id='tabs_to_monitor']", &block)
end
This handler captures the content of the xpath you want to observe, and then waits for that block to update before executing the code inside the block. This way, no arbitrary waiting (like using sleep 5 and hoping the request is done). Then, you use is like this:
$ff = Firefox.new
$ff.goto("www.yourajaxyapp.com")
$ff.elements_by_path("//tr[@id='blah']").first.click
after_tab_updates do
$ff.elements_by_xpath("//tr[@id='inside_of_tabs']").first.click
end
This way you’ll be sure to know that the page is loaded before your next request fires.
If you have a better way, let me know, but I couldn’t find a good existing solution to this.