With capybara-webkit properly installed, just add an example like this:
Read on to learn how to set up RSpec, capybara, and capybara-webkit in a new Rails app.
1. Configure Rails for RSpec
Rails doesn’t use RSpec out of the box, so after creating a new Rails project you’ll need to add this gem to your Gemfile and run
group :test do gem 'rspec-rails', :group => :development end
config/initializers/generators.rb, tell Rails to use RSpec format whenever it generates test code. This applies to things like
rails generate [controller|model|resource|scaffold] You can also disable generated code for specs that you don’t find useful.
Rails.application.config.generators do |g| g.test_framework :rspec, :view_specs => false, :controller_specs => false, :request_specs => false, :routing_specs => false end
Now run the RSpec installer to create the
spec directory and the
spec_helper.rb configuration file:
rails generate rspec:install
2. Install Qt
You’ll need to have the Qt libraries in order to install capybara-webkit. Here’s how to do it on the Mac, assuming you have homebrew:
brew install qt
If that fails, or if you’re on a different platform, check the capybara-webkit wiki for instructions.
3. Install capybara and capybara-webkit
Add these gems to your Gemfile and run
group :test do gem 'capybara' gem 'capybara-webkit' gem 'database_cleaner' end
Capybara-webkit runs your Rails app separately from your RSpec code, which means that the database transaction test strategy used by Rails leads to problems. The database_cleaner gem provides a nice workaround, which is why we need it in addition to the capybara gems.
spec_helper.rb and configure capybara, capybara-webkit, and database_cleaner as follows:
Browser-driven tests are known as feature specs in RSpec terminology, and belong in
spec/features/home_spec.rb file like this:
The most interesting part is
:js => true. This RSpec metadata is what instructs capybara-webkit to run the test against a real HTTP version of your app, using the WebKit browser engine (similar to what powers Safari and Chrome).
5. Running the test
If everything goes well, you should see this output when running
/Users/mbrictson/.rbenv/versions/2.0.0-p247/bin/ruby -S rspec ./spec/features/home_spec.rb . Finished in 1.11 seconds 1 example, 0 failures Randomized with seed 44770
Once you have a nice test suite running locally, considering automating it using a continuous integration server. Our tutorial on Running capybara-webkit specs with Jenkins CI will help you get started.
Finally, if you like the RSpec and capybara practices outlined in this post, check out our rails-starter template for new Rails projects. RSpec, capybara, and capybara-webkit are baked right in, along with many other useful tools and techniques.comments powered by Disqus