Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 134 ยท Testing and Tooling

RSpec Overview

Learn how RSpec works in Ruby, the most popular testing gem: describe, it, expect, matchers, let, doubles. Includes a runnable mini-RSpec built from scratch.

RSpec is the most widely used testing library in the Ruby world, especially in Rails projects. It is a gem, not part of Ruby itself, and it gives tests a different flavor from Minitest: you write specifications that read almost like English sentences, such as "a new stack is empty" or "withdrawing too much raises an error".

RSpec is a third-party gem, and our code runner has no network, so real RSpec cannot run on this website. The RSpec snippets in this lesson are read-only and labelled as such. To still let you experiment, we build a tiny working imitation of RSpec's core, about a hundred lines, and run it. That is the best way to understand RSpec anyway: once you see that describe, let and expect(...).to are ordinary Ruby methods and blocks, the framework stops being magic.

Is RSpec available here?

First, a quick check of what the runner has. This tries to load the gem and reports what happens.

Ruby Checking whether RSpec can be loaded

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The LoadError is the expected result: the runner only has the gems that ship with Ruby, and RSpec is not one of them. In your own project you install it with Bundler (bundle add rspec --group test, then bundle exec rspec --init). See RubyGems and Bundler.

What an RSpec file looks like

This is a read-only example (it needs the rspec gem). It specifies a Stack class that you would keep in lib/stack.rb:

Ruby
# spec/stack_spec.rb  (read-only: needs the rspec gem)
require_relative "../lib/stack"

RSpec.describe Stack do
  subject(:stack) { Stack.new }

  describe "#push" do
    it "adds an item on top" do
      stack.push(1)
      expect(stack.peek).to eq(1)
    end
  end

  describe "#pop" do
    context "when the stack is empty" do
      it "returns nil" do
        expect(stack.pop).to be_nil
      end
    end

    context "when the stack has items" do
      before { stack.push(1).push(2) }

      it "returns the last item pushed" do
        expect(stack.pop).to eq(2)
      end

      it "removes the item" do
        expect { stack.pop }.to change(stack, :size).by(-1)
      end
    end
  end
end

Run it with bundle exec rspec, or with bundle exec rspec spec/stack_spec.rb:12 to run the example on line 12 only. The vocabulary is small:

Word Meaning
describe / context A group of examples. describe names a thing or a method ("#push"), context names a situation ("when the stack is empty")
it One example, a single behavior with its own description
expect(actual).to matcher The assertion: compare a value with a matcher
expect { ... }.to matcher The block form, for exceptions, output and changes
before / after Code that runs before or after each example
let(:name) { ... } A lazily created, per-example helper value
subject The object under test; subject(:stack) also names it

How expect(...).to eq(...) works

The strange part for newcomers is the syntax expect(x).to eq(y). There is nothing special about it. expect(x) returns an object that remembers x. eq(y) returns a matcher object that knows how to compare. to hands the value to the matcher and raises an error if it says no. We can build the idea in a few lines.

Ruby expect, to and eq in a few lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because Ruby lets you leave out parentheses, expect(2 + 2).to eq(4) reads like a sentence. Real RSpec has the same shape, plus roughly a hundred matchers (be_nil, include, match, raise_error, change, be_within, have_attributes, ...) and much better failure messages, with diffs for long strings and nested data.

A working mini-RSpec

Now we assemble the pieces into a runnable imitation: describe/context, it, before, let, and the matchers eq, be_nil, include and raise_error. Study it as a lesson in blocks: instance_eval, instance_exec and define_singleton_method, covered in instance_eval and class_eval, do all the work.

Ruby MiniSpec: describe, it, let, before and expect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output uses RSpec's documentation format: nested group names with the examples indented below them. Let us see how each piece maps to something you know.

  • describe at the top is a plain method that creates a Group and evaluates the block inside it with instance_eval. That is why let, before, it and the nested describe look like keywords but are just methods of Group.
  • it only stores the block. Nothing runs until MiniSpec.run walks the tree. RSpec works the same way, which is why the file is read completely before the first example starts.
  • For every example a fresh Context is created, so examples cannot influence each other. before hooks of the parent groups run first, then the example block runs with instance_exec, with self set to that context.
  • let defines a method on the context that computes its block once and memoizes it: the first call to stack builds the stack, later calls in the same example return the same object, and the next example starts over.
  • The deliberately wrong example fails, so the report ends with Failure: when the stack has items is wrongly expected to keep both items: expected 1 to eq 2 and the line 6 examples, 1 failures. Real RSpec prints more detail, but the idea is the same: a failure is an exception, caught and counted.

Real RSpec adds a lot of polish to this skeleton: subject, shared_examples, filters and tags, random ordering, --only-failures, one-line output, parallel runs through other gems and plenty of matchers. The fundamental model, though, is what you just ran.

Matchers worth knowing

These are real RSpec matchers (read-only; they need the gem):

Ruby
expect(value).to eq(5)                       # ==
expect(value).to eql(5)                      # eql? (5 is not 5.0)
expect(value).to be(object)                  # same object (equal?)
expect(value).to be_nil
expect(value).to be_truthy                   # anything but nil/false
expect(0.1 + 0.2).to be_within(0.001).of(0.3)
expect(list).to include(3, 4)
expect(list).to contain_exactly(3, 2, 1)     # any order
expect(name).to match(/\A[A-Z]/)
expect(user).to have_attributes(name: "Ada")
expect(thing).to be_a(Comparable)
expect { Integer("x") }.to raise_error(ArgumentError, /invalid value/)
expect { stack.push(1) }.to change(stack, :size).by(1)
expect { puts "hi" }.to output("hi\n").to_stdout
expect(stack).to be_empty                    # calls stack.empty?

The last line shows a feature people love: any method that ends with ? becomes a matcher. be_empty calls empty?, be_valid calls valid?, and have_key(:a) calls has_key?(:a). It is implemented with method_missing, the technique from method_missing and respond_to_missing?.

Doubles and message expectations

RSpec also ships with tools to replace collaborators in tests (doubles, stubs and spies). This is a read-only example; Test Doubles shows the same ideas with hand-written objects and Minitest, which do run here.

Ruby
RSpec.describe Checkout do
  it "charges the card once" do
    gateway = instance_double(PaymentGateway)
    allow(gateway).to receive(:charge).and_return(:ok)

    result = Checkout.new(gateway).pay(1999)

    expect(gateway).to have_received(:charge).with(1999).once
    expect(result).to eq(:ok)
  end
end

instance_double(PaymentGateway) creates a stand-in that checks the real class: calling a method that PaymentGateway does not define raises an error, so a double cannot silently drift from the real object. allow(...).to receive(...) stubs a method, and have_received verifies the call afterwards.

RSpec or Minitest?

Both are excellent, and the same tests can be written in either. Here is the stack example in Minitest, which does run here:

Ruby The same Stack behavior in Minitest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Minitest RSpec
Where it comes from Ships with Ruby Gem, installed with Bundler
Style Plain Ruby classes and methods (also a spec style) A DSL of describe, it, expect
Learning curve Small: classes and assert_* Larger: many matchers and concepts
Speed Very fast to load Noticeably heavier to load
Failure output Plain, compact Rich: diffs, colors, formats
Mocking Minitest::Mock and stub, or hand-written fakes Built-in doubles and spies
Typical home Rails default, many gems Many Rails apps, large teams

Neither is "the right one". Choose what your team already uses, and be able to read both. The skills that matter more than the library are the ones from Test-Driven Development: small examples, one behavior per test, independent examples and readable names.

Writing good specs

  • Describe behavior, not implementation. it "returns nil" beats it "calls Array#pop".
  • One expectation per idea. Several expect lines are fine when they describe the same behavior, but a long example is a sign you need two.
  • Use context for situations. "when the stack is empty", "with an invalid email" keep the tree readable.
  • Prefer let over instance variables in before, since let is lazy and makes dependencies explicit; but do not nest let so deeply that nobody can see where a value comes from.
  • Make the sentence read well. RSpec.describe Stack plus describe "#pop" plus it "returns nil" should read as a sentence when joined.

Common mistakes

  • Forgetting that it blocks do not run on definition. Code you put directly in a describe body runs once while the file loads, not per example.
  • Sharing mutable state between examples in constants or class-level variables. Use let or before.
  • Overusing mocks. A test that mocks everything checks the mock, not your code.
  • Eager let! everywhere. let! runs before each example even if unused; reach for plain let first.
  • Relying on example order. RSpec can run in random order, and so should your tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can't the RSpec examples in this lesson be run on the website?

    RSpec is installed from RubyGems. The runner only has the standard library and bundled gems, so require "rspec" raises LoadError.
  2. 2. In expect(x).to eq(5), what is eq(5)?

    eq(5) returns a matcher. expect(x) wraps the value, and to(matcher) asks the matcher to check it, raising an error on failure.
  3. 3. What does let(:stack) { Stack.new } do in an RSpec group?

    let defines a method that builds its value on first use and remembers it during that example. Every example gets a fresh value.
  4. 4. What is the difference between describe and context in RSpec?

    They are aliases that behave the same way. The convention is to use describe for the subject and context for conditions such as "when the stack is empty".
  5. 5. In our MiniSpec, why is a fresh Context object created for each example?

    A new context means new memoized let values and no leftover instance variables, which keeps examples independent.

Summary

  • RSpec is a third-party gem for expressive tests: describe and context group, it defines an example, expect(...).to matcher asserts.
  • expect(x).to eq(y) is plain Ruby: a wrapper object, a matcher object and a method that raises on mismatch.
  • before, let and subject set up each example; let is lazy and memoized per example.
  • RSpec adds many matchers, doubles (instance_double, allow, have_received) and rich failure output.
  • Minitest ships with Ruby and is smaller and faster; RSpec has a bigger vocabulary. Both test the same things.
  • RSpec cannot run on this website, so you saw read-only snippets and a runnable mini-RSpec that shows how it works inside.

Next: Test Doubles