This is a quick-and-dirty tutorial to set up automated browser tests with the following tools:
- RSpec is a Ruby behavior-driven development framework.
- Capybara is an acceptance test framework that simulates how a real user would interact with your web app.
- Selenium Webdriver automates browsers like Firefox.
Since browser tests are generally isolated from the rest of your project, the language of the web app is irrelevant. I wrote this guide after setting up a test suite for a Node.js web app.
I assume here that you have already installed and set up Ruby exactly the way you like it. I recommend the excellent RVM for that. I used Ruby 1.9.2 for this tutorial. You should also have a recent version of Firefox.
Let’s start by writing a Gemfile to install everything we need.
1 2 3 4 5 6 7 8 9 10 11 12
If it’s not part of your Ruby setup already, run
gem install bundler. This will install what you need to use the Gemfile. Once that’s done, simply run
bundle install to download and install all the gems and their dependencies.
You should now have a new
Gemfile.lock file that lists the exact versions of the gems that were installed.
We still need a few files in place before we can run tests.
I prefer to use Rake to run my tests. If you’re not in a Ruby on Rails project or using another framework that includes Rake, create a Rakefile:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
This sets up RSpec so that you can run your tests with
bundle exec rake spec or
bundle exec rake (default task). Note the
bundle exec part which makes sure Rake is executed in the context of your installed gems, which will probably save you some trouble.
As indicated in the Rakefile comments, you can customize RSpec settings by adding a
.rspec file. I like activating the following options so I have a nicely formatted test output and colors. Run
bundle exec rspec --help if you want to know what other options you can tweak.
1 2 3 4
The last configuration file we need is a spec helper so that we don’t have to require everything in each test file. The following one will do that quite nicely. Note at the end that we switch the Capybara driver to Selenium, as it’s not using that by default.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 2 3 4 5 6 7 8 9 10 11
And that’s pretty much it. Run
bundle exec rake spec to run the test. This will run all
*_spec.rb files in the spec directory. Firefox will magically open, load the required page and the contents will be checked.
- Ruby: 1.9.2
- Capybara: 1.1.2
- RSpec: 2.11.0
- Rake: 0.9.2.2
- Bundler: 1.1.0