Integration Testing Setup with RSpec 2 and Capybara
NOTE: This is an update to a post I made a while back on using Capybara with RSpec 1 for integration testing. This post is specifically for using Capybara with RSpec 2! The setup information is different but the example is the same.
RSpec 2 has introduced a ton of great new features to make our spec suite better. Writing integration specs in RSpec is easier now, too. Well, maybe not easier, but definitely prettier. If you already have RSpec integration specs in your project and are upgrading from RSpec 1, then you will want to start by removing any requires or includes from your
spec_helper.rb or support/capybara.rb files. Those inclusions are still necessary, but have a new home now. Next up, put the necessary requires in your Gemfile.
Run a quick bundle install and you should be good to go from a gem perspective. Run rails generate rspec:install to generate the basic rspec setup for the new version. Note that the spec_helper.rb has changed, so make sure you merge any changes you had into the new file. Now we need to add the piece that ties RSpec and Capybara together for your integration tests. Paste this file into spec/support/integration_example_group.rb. All the Capybara requires and includes happen here, so you no longer need to do it in your spec_helper.rb or support/capybara.rb.
Just to make sure all this is working properly, go ahead and run rake. If this doesn’t work, you need to fix whatever the problem is before moving on. Now on to Capybara! By default it uses the rack-test driver, which is similar to webrat in that it is headless and does not run javascript. Unless you have a very javascript intensive app, the rack-test driver should handle the majority of your test cases. The really cool thing about Capybara is that you can use another driver like selenium when you need javascript and rack-test when you don’t. Now let’s test a simple sign in process. Create a file called spec/integration/guest_signs_in_spec.rb and fill it in like so. Be sure to change the field, button, and link labels to match your actual screens.
That is a trivial example and you would typically want to make more numerous and comprehensive asserts than that, but it should get you going with your first test. Now that you have a modern integration test setup, I expect to see the quality of your app improve dramatically! Happy TDD’ing!