Rails is built using Ruby, so you can do all your testing using Ruby’s built-in Test::Unit or Minitest gems. But a limitation of these libraries is that they are not built specifically for web applications. Once you get past testing out the basic functionality of your controllers and models, you’ll need to do a “real-world test,” or what’s also know as “acceptance” or “integration” testing. For this, you’ll need something that can mimic the behavior of using a browser.
To do this, the Rails ecosystem offers a variety of options, two of which I greatly recommend – RSpec with Rails and Capybara.
To start with, you should be using RSpec with Rails. It helps additionally if you have the shoulda gem installed as well – it gives you a set of basic helper functions that let you assert expectations about your models and controllers in a simple way.
The basic RSpec configuration, including the use of helpers for Devise, are available in this Github repo – there is a branch that works for Rails 3 (specifically, 3.2.16) and one for Rails 4 (specifically, 4.0.1.)
Here are some steps worth noting when you start with using RSpec:
- You need the rspec-rails gem in your Gemfile, to get scaffolding to automatically generate RSpec specifications for you.
- It’s worth also adding the ‘shoulda-matchers’ gem – you get a few matchers that help you check for model validations really easily.
- You need to add the rspec-rails gem to both the development and the test group in your Gemfile.
- When generating automatic RSpecs, Rails will try to intelligently create stub models or attributes to create and update models. However, this process is a little broken – all integer and float attributes are assigned the same value, which might cause some of the tests to fail. One situation where this causes a problem is in testing views – the way the assertions are written for the default index view generated for in a scaffold, they assume that each attribute will in fact have different values which is not what the scaffold does when there multiple integer or float attributes in a model.
Of course, that’s just the beginning – writing good tests is a life-long learning process, but RSpec gives you a lot of awesome tools to make the journey easier!