Integration Testing with Capybara and Selenium

You may not realize this, but your javascript is full of bugs. Because of the ghetto nature of most applications’ javascript, it is easy to break things that seem unrelated to what you are currently working on. It can be tough to know what exactly is acting on what parts of your site, depending on who did it, when it was written, what libraries were used, etc.

A few options exist for javascript-enabled integration testing, but the easiest to set up and most reliable is still selenium. With capybara, it is simply a matter of tweaking some settings and turning it on where you need it.

To set up selenium, you can start by adding database_cleaner to the test group in your Gemfile.

gem 'database_cleaner', ‘0.5.2’

Now you need to add the following code to spec/support/database_cleaner.rb.

require 'database_cleaner'

Spec::Runner.configure do |config|

  DatabaseCleaner.strategy = :truncation

  config.before :each do
    Capybara.reset_sessions!
    DatabaseCleaner.clean
  end

end

Then, you need to turn off transactional fixtures in your spec_helper.rb.

config.use_transactional_fixtures = false

To set up a specific test to use the selenium driver, you just need to put before and after blocks at the start of your test.

before(:all) { Capybara.current_driver = :selenium }
after(:all) { Capybara.use_default_driver }

Now when you run this test, you will see a Firefox window pop and the browser will dance for you. You shouldn’t need to change anything else in your tests for it to work thanks to the capybara dsl.