Thursday, April 5, 2012

The perfidy of AJAX and surprise attacks using when_present

If you are testing an asynchronous website which uses Javascript to create widgets, hide and show elements, etc, watir-webdriver can have trouble seeing them.  Watir does great waiting for pages to load without telling it specifically to do so.  However, when your AJAX calls change a website's Javascript, Watir doesn't know it needs to wait.

For example, my company has something called the Dashboard.  The Dashboard is a little tab that you can click and shoot out of the left-hand side of the page.  It's nifty, but my scripts were occasionally failing due to the AJAX not loading the page quickly enough.  An annoying, intermittent problem that took me a while to figure out and fix.

The solution is a little method called when_present.  I have a little method called Dashboard::switch_client.  It ensures I'm on the correct client site after I log in based on an Environment variable.

  def switch_client
    self.dashboard_button.click
    self.company_list.select @client
    self.dashboard_button.click
  end

My problem was in using the select box.  Sometimes it wasn't yet available.  Here's my solution:

  def switch_client
    self.dashboard_button.click
    self.company_list.when_present.select @client
    self.dashboard_button.click
  end

I now do this for all my menus and sub menus, calendar widgets, and any other widgets I have on the page.  when_present gives an element 30 seconds to appear by default before failing the test.  Over laggy connections, that's very helpful.

You can find more information and a couple similar methods for waiting for elements, including one that waits for an element to disappear in the RDoc: http://jarib.github.com/watir-webdriver/doc/Watir/Element.html#when_present-instance_method

No comments:

Post a Comment