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.
The 60-second answer
Section titled “The 60-second answer”“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.”
Structure and matchers
Section titled “Structure and matchers”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 endendConvention: 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-sensitiveexpect(value).to equal(expected) # equal? — object identityexpect(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, let! and subject
Section titled “let, let! and subject”let(:user) { create(:user) } # lazy: built on first referencelet!(:order) { create(:order, user:) } # eager: evaluated in a before hooksubject(:service) { described_class.new(user) }letis memoised per example — a fresh value for eachit.- Overriding a
letin a nestedcontextis 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 explicitbeforewhen the reason is a side effect rather than data.subjectis aletthatis_expecteduses:it { is_expected.to be_valid }.before(:each)runs per example andafter(: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 and factories
Section titled “Shared examples and factories”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 } } endend| 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.
Request and system specs
Section titled “Request and system specs”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) endendRSpec.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") endendRequest 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.
Follow-up questions
Section titled “Follow-up questions”- What is the difference between
letandlet!, and when does it bite? - Why is
before(:all)dangerous? - When would you use a request spec instead of a system spec?
- How do you test a background job and its mailer?
Common traps
Section titled “Common traps”createeverywhere. 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 randomto expose it. - Giant
beforeblocks. Hidden setup makes failures hard to diagnose. - Over-stubbing. If everything is a double, the test cannot fail for the right reason.