This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

RSpec Cheatsheet

A comprehensive reference guide for RSpec: BDD testing in Ruby, describe, context, it, matchers, let, subject, mocks, and spies.

· Published

RSpec is a Behavior-Driven Development (BDD) testing tool for Ruby.

Basic Spec Structure

RSpec.describe Calculator do
  let(:calculator) { Calculator.new }

  describe "#add" do
    context "when adding positive numbers" do
      it "returns the arithmetic sum" do
        expect(calculator.add(2, 3)).to eq(5)
      end
    end

    context "when given invalid input" do
      it "raises an ArgumentError" do
        expect { calculator.add(2, "x") }.to raise_error(ArgumentError)
      end
    end
  end
end

Core Matchers

# Equality
expect(actual).to eq(expected)       # Value equality (==)
expect(actual).to be(expected)       # Object identity (equal?)

# Truthiness & Predicates
expect(actual).to be_truthy
expect(actual).to be_nil
expect(user).to be_active            # Calls user.active?

# Collections
expect(list).to include("ruby")
expect(list).to match_array([1, 2])  # Same elements regardless of order
expect(list).to be_empty

# Comparisons
expect(value).to be > 10
expect(value).to be_between(1, 100).inclusive

# Errors & Throws
expect { risky_call }.to raise_error(StandardError, /message/)
expect { safe_call }.not_to raise_error

Mocks & Stubs (rspec-mocks)

# Method stubbing
allow(user).to receive(:name).and_return("Alice")

# Expectation on method invocation
expect(notifier).to receive(:send_email).with("[email protected]").once

# Double (mock object)
mock_service = double("PaymentService", charge: true)

References

Related topics