Friday, October 21, 2011

Monkey Patching Firefox Race Conditions For Watir-WebDriver/Cucumber

If your team is like my team, you're trying to find ways to automate everything. Perhaps you're also using watir-webdriver to run browser based tests with Cucumber. This works great locally, but when you try to run your tests on a CI environment you start to run into some very strange problems with Firefox testing.  You start to get errors around not being able to find the h1 tag on your page.  You look at the screen shot you've generated using a method similar to this, and you find that your screenshot shows the text that contains the h1.  In fact, your error dumped html file also shows the h1 tag:

You've run into selenium issue 2099.  It appears what happens with this error is that the test is executing before the page has fully loaded, causing it to fail.  Old school race conditions.  Nice.

So how do we get around this?  There's been a few postings on how to handle this with Capybara, but what about tools that use selenium-webdriver more directly?  Here's a monkey patch that hacks over the Ruby bindings to enable tools like watir-webdriver to retry.  This patch will retry the find until selenium-webdriver receives an error that is not related to the strange InvalidSelectorError that it gets when the Firefox isn't done loading the page. I just stuff this file into the support directory in a Cucumber suite.

Since this is hacky and a monkey patch, I'm very keen on ideas on how to improve this implementation, since my Ruby skills are very raw.