February 24, 2012

My capybaras are too many

WORDS BY   Matej Artač

POSTED IN   tutorial | ruby | capybara | cucumber | continuous integration

Cucumber and Capybara, exploiting the Selenium driver, is a powerful combination for running automated tests of the web GUI. Most of the tutorials out there show how simple it is to create a session and use it for testing AJAX-based web sites.

What they fail to show is that in a serious test, there are going to be tens or hundreds of scenarios run in a single sweep. That wouldn’t have been a problem in itself. However, each scenario step definitions start with a new Selenium session. Each one opens a new FireFox browser. And none of the scenario closes the browser when it is done. How do I prevent the Capybaras from multiplying, crashing my desktop?

Luckily, the Selenium driver has a way to control the browser. Assuming we initialised the driver as follows:

require "rubygems"
require "capybara"

@session = Capybara::Session.new(:selenium)

then we can have the browser close by calling:


This line needs to go into the hook called whenever a scenario finishes running. We can create a file called capybara.rb in features/support with the following content:

# contents of features/support/capybara.rb
After do