How to run Selenium (and Cucumber) in your CI environment without blowing up your Jenkins machine

I’m running some prototypes with Selenium/WebDriver and Cucumber (see my recent post on Cucumber). Initially, I just loaded a WebDriver in my step definitions class and ran my unit tests based on queries off the WebDriver’s results.

Here’s what I mean. For this Cucumber feature file:

blogging-feature

I implemented these step definitions, which work as long as nothing goes wrong:

If something does go wrong in my test above, however, you’ve got a browser window just sitting open and eating up resources. (Assuming your Jenkins or whatever job doesn’t clean these up.) I could probably rearrange my tests to bring the WebDriver down earlier, but there’s always that chance that things will blow up out of sequence.

The IBM DeveloperWorks folks have a great quickstart guide to implementing Cucumber with Selenium on Java. It’s smarter in that adds a shutdown hook to the VM to clean up, but it’s incomplete. I added a comment to their post, but in the event that they don’t fix it… hopefully this will help you.

You need to have both the close() and quit() methods, as I did in the following adaptation of their code:

You should see your Firefox browser boot up, hit my blog (thanks for the traffic!) and then come down even if your step definitions blow an exception or fail an assertion.

I’m still trying to find the best practices with Selenium, Cucumber, et al, so please let me know if I’m missing something big on this post. Thanks in advance!

UPDATED 2014-08-01: because of some threading issues, I updated the code a little to add the synchronized keyword to the close() method. I also added some better handling so that the shared object doesn’t dump occasional stack traces in your console (or worse, cause you to fail a test unnecessarily).

UPDATE 2014-08-19: forgot to mention that I was using this Maven dependency and version:

Leave a Reply

Your email address will not be published. Required fields are marked *