RSpec 3 Cheatsheet

posted in: ones and zeros | 0

This is a quick and dirty reference guide to the absolute basics of RSpec 3.

My experience has been that beginner programmers don’t get enough practice with testing, and that a lot of RSpec references don’t specify which version they’re using and aren’t necessarily updated to reflect the evolution of best practices (like the switch from should to expect).

Describe It

The general pattern to follow is to have a describe statement that wraps around it statements which do the actual heavy lifting:

describe Order do
  it "human-readable does-something description" do
    # expect statement - your test! - goes here
  end
end

Only one expectation per it statement!

Contextualize

You can also create a context to organize your tests according to the various situations you’re testing:

describe Order do
  context "invalid user" do
    it "does not add item to cart" do
      # expect statement
    end

    it "redirects to user login" do
      # expect statement
    end
  end
end

Matchy-Matchy

There are a variety of kinds of things you can test for, and some of them are easy to mix up with each other. Some built-in matchers for testing objects:

expect(something).to eq(something)    # equivalence
expect(something).to be(something)    # identity

expect(something).to be false         # value is false
expect(something).to be_falsey        # value is "falsey"

When you want to test something other than an object, you can use a block:

expect{
  # do something
  }.to change {something}.by(1)

expect{
  # do something
  }.to raise_exception(ExceptionName)

Resources

There are quite a few resources out there that do an excellent job of contradicting each other, so try to get at least a couple different opinions on something (like before vs let) before you use it!

  • Abi Noda’s Rspec Best Practices is a good place to start
  • Relish’s RSpec Expectations 3.2 - the actual docs are less painful than some
  • BetterSpecs.org has examples of good vs. bad implementation
  • Practice using RSpec with Rails via the Everyday Rails book (there’s a link to the free PDF at the bottom – I’ve only read the PDF and would have preferred it took a TDD-from-the-very-beginning approach, but it’s still good for RSpec practice)