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:
RSpec.describe Cart dolet(:cart) { Cart.create }let(:book_one) { products(:ruby) }let(:book_two) { products(:two) }before docart.add_product(book_one).save!cart.add_product(book_two).save!endit "can have multiple products added" doexpect(cart.line_items.size).to eq(2)endit "calculates the total price of all products" doexpect(cart.total_price).to eq(book_one.price + book_two.price)endend
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:
group :development, :testdo 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 ...