Skip to content

RSpec

RSpec is Ruby’s dominant testing framework and, more importantly, a vocabulary: describe for structure, context for a situation, it for one expectation about behaviour. It appears in almost every Rails codebase, so interviewers expect fluency rather than familiarity.

“describe groups examples by the thing under test, context groups them by a situation, and it states one behaviour. Expectations use matchers like eq, include, raise_error and change. let defines a lazily evaluated, memoised helper scoped to the example, let! forces it into a before hook, and subject is the thing under test that is_expected uses. before(:each) runs per example; avoid before(:all), which leaks state. Factories build valid records with create, build and build_stubbed, which is cheaper and more explicit than fixtures. Request specs exercise the HTTP stack without a browser; system specs drive a real browser through Capybara for the end-to-end layer.”

spec/models/order_spec.rb
RSpec.describe Order do
describe "#total" do
context "when the order has no items" do
it "returns zero" do
expect(Order.new.total).to eq(0)
end
end
context "when a discount applies" do
subject(:order) { build(:order, discount: 0.2) }
before { order.line_items << build(:line_item, price: 100) }
it "applies the discount to the subtotal" do
expect(order.total).to eq(80)
end
end
end
end

Convention: describe takes a class or method name ("#" for instance methods, "." for class methods); context starts with “when”, “with” or “without”; it completes “it …”.

expect(value).to eq(expected) # ==
expect(value).to eql(expected) # eql? — type-sensitive
expect(value).to equal(expected) # equal? — object identity
expect(list).to contain_exactly(2, 1)
expect { action }.to change { Order.count }.by(1)
expect { action }.to raise_error(ArgumentError, /invalid/)
expect(response).to have_http_status(:created)
expect(page).to have_content("Saved")

Prefer one expect per example, or wrap related assertions in aggregate_failures so a failure does not hide the rest.

let(:user) { create(:user) } # lazy: built on first reference
let!(:order) { create(:order, user:) } # eager: evaluated in a before hook
subject(:service) { described_class.new(user) }
  • let is memoised per example — a fresh value for each it.
  • Overriding a let in a nested context is the clean way to vary setup.
  • let! exists because a side effect nobody references (a record existing in the DB) still has to happen. Prefer an explicit before when the reason is a side effect rather than data.
  • subject is a let that is_expected uses: it { is_expected.to be_valid }.
  • before(:each) runs per example and after(:each) always runs, even on failure. before(:all) runs once per group and leaks instance variables between examples — avoid it.

Use travel_to/freeze_time (ActiveSupport) instead of sleep. Sleeping tests are slow and flaky.

shared_examples + it_behaves_like factor out behaviour shared across different classes; if two describes share only setup, a factory trait or a helper is clearer, and shared_context is for shared setup. Factories replace fixtures with explicit, valid records:

it_behaves_like "an authenticatable endpoint" do
let(:path) { orders_path }
end
FactoryBot.define do
factory :order do
user
discount { 0 }
trait(:paid) { status { :paid } }
end
end
Strategy Hits the DB Use for
create Yes Anything the code queries
build / build_stubbed No Validations and fast unit tests
attributes_for No Params hashes for request specs

Prefer the cheapest strategy that still tests the behaviour; create in a unit test usually means the test is an integration test in disguise.

spec/requests/orders_spec.rb
RSpec.describe "Orders API", type: :request do
it "creates an order" do
expect {
post orders_path, params: { order: { item_id: item.id } }, as: :json
}.to change(Order, :count).by(1)
expect(response).to have_http_status(:created)
end
end
spec/system/checkout_spec.rb
RSpec.describe "Checkout", type: :system do
before { driven_by(:cuprite) } # or :selenium with headless Chrome
it "completes a purchase" do
sign_in_as(create(:user))
visit cart_path
click_button "Checkout"
fill_in "Card number", with: "4242 4242 4242 4242"
click_button "Pay"
expect(page).to have_content("Order confirmed")
end
end

Request specs are the workhorse for controllers: fast, no browser, real routing and middleware. System specs run a real browser and are the only layer that proves JavaScript works — use them sparingly, for critical flows. Feature specs are the older name for the same idea.

  1. What is the difference between let and let!, and when does it bite?
  2. Why is before(:all) dangerous?
  3. When would you use a request spec instead of a system spec?
  4. How do you test a background job and its mailer?
  • create everywhere. Slow suite, and unit tests that are really integration tests.
  • Asserting on implementation. expect(service).to receive(:call) proves nothing about output.
  • Shared state between examples. Order-dependent failures; run with --order random to expose it.
  • Giant before blocks. Hidden setup makes failures hard to diagnose.
  • Over-stubbing. If everything is a double, the test cannot fail for the right reason.