< mockra >

Javascript Testing with RSpec and Capybara - 24 May 2012

Setting up javascript testing with Capybara can be done in a few steps. Unfortunately transactional fixtures aren’t compatible with Selenium, the tool Capybara uses for JS testing. To circumvent this issue, you’ll need to disable transactional fixtures in your spec_helper.rb. You’ll also want to use a tool like database_cleaner.

To get everything setup for Capybara, you’ll want to include gem 'database_cleaner' in your Gemfile. Add the following lines to your spec_helper file as well.

DatabaseCleaner.strategy = :truncation

RSpec.configure do |config|
  config.use_transactional_fixtures = false
  config.before(:each) { DatabaseCleaner.start }
  config.after(:each) { DatabaseCleaner.clean }

You can then setup your specs as follows to start testing javascript. You’ll also need Firefox installed by default, but I’ll go over the appropriate steps for setting up your environment for Chrome as well.

require 'spec_helper'

describe "Articles" do
  describe 'new', js: true do

Setting up Selenium to use Chrome requires that you add the following configuration to the bottom of your spec_helper.

Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, :browser => :chrome)

You’ll also need to download the ChromeDriver server, which can be found here. Once you download the appropriate file, you need to add it to your path. The following terminal command will work for OS X users.

mv ~/Downloads/chromedriver /usr/local/bin/

When you run your tests that require javascript, a Chrome window will open and run the specs now. Good luck testing!