Testing with RSpec

Learn to test code with RSpec

We'll cover the following...

Overview

RSpec is an alternative to MiniTest, which Rails uses. It’s different in almost every way, and many developers prefer it. Here’s what one of our existing tests might look like when written in RSpec:

Press + to interact
RSpec.describe Cart do
let(:cart) { Cart.create }
let(:book_one) { products(:ruby) }
let(:book_two) { products(:two) }
before do
cart.add_product(book_one).save!
cart.add_product(book_two).save!
end
it "can have multiple products added" do
expect(cart.line_items.size).to eq(2)
end
it "calculates the total price of all products" do
expect(cart.total_price).to eq(book_one.price + book_two.price)
end
end

It almost looks like a different programming language! Developers that prefer RSpec like that the test reads like English. For example, “Describe Cart, it can have multiple products added, expect cart.line_items.size to eq 2 in line 12.”

We’re going to quickly go through how to write tests in RSpec without too much detail. Although many developers that use RSpec set it up from the start of a project, we don’t have to. RSpec can be added at any time, which is what we’ll do here.

Add RSpec-rails to our Gemfile, putting it in the development and test groups:

Press + to interact
group :development, :test
do gem 'rspec-rails'
end

After we bundle install, a new generator will set up RSpec for us:

bin/rails generate rspec:install
  create .rspec
  create  spec
  create  spec/spec_helper.rb
  create  spec/rails_helper.rb

Verify the configuration is working by running ...