ParsaLabs | Blog

A publication about the web and more.

Setting Up and Using Capybara With Rails

| Comments

Capybara is an exellent choice for writing integration tests in your Rails apps. Rails doesn’t come with Capybara built in, but never worry, as setting up and using Capybara is reletively smooth. In this post, I intend to show you how to do exactly that. So, let’s get to it:

First add the following lines to your Gemfile

1
2
gem 'capybara'
gem 'capybara-webkit'

and run the bundle command to install them. The second gem is to enable the webkit driver, which allows Capybara to run (and test) javascript on the page.

Next, add the following to your test_helper.rb file:

1
2
3
4
5
require 'capybara/rails'

class ActionDispatch::IntegrationTest
  include Capybara::DSL
end

Capybara helps you test web applications by simulating how a real user would interact with your app. To achieve that, you need to mimick user actions such as visiting urls, clicking links/buttons, filling in form data, etc. And that’s exactly what Capybara DSL allows you to do (and more), with its extensive library. Find the Reference here.

Now, we are going to have to set a javascript driver for Capybara to use. You have a few options here, but I prefer Webkit, because it is much faster than selenium. Open your config/environments/test.rb file, and add the following line to it:

1
Capybara.javascript_driver = :webkit

Note that for this to work, you need to have qt library installed. on Mac it’s as simple as brew install qt.

At this point we are done with the setup. To use Capybara, you first need to generate an integration test with the following rails command:

1
rails generate integration_test <Enter the desired name of your test here>

Capybara uses rack_test as default driver which is very fast but doesn’t support javascript. We need to be able to (temporarily) switch to webkit driver when our test involves running and testing javascript. To do that, you can either use your class setup/teardown blocks…

1
2
3
setup do
  Capybara.current_driver = Capybara.javascript_driver
end

..or inside the test case itself:

1
2
3
4
5
6
7
8
9
test "javascript works" do
  # switch to webkit driver
  Capybara.current_driver = Capybara.javascript_driver

  # ... write your test here.

  #switch back to default driver
  Capybara.use_default_driver
end

Keep in mind that switching the driver creates a new session, so you may not be able to switch in the middle of a test.

And that’s about it! Capybara is a very simple and powerful tool for testing. I highly recommend you start using it.

Comments