describe, Matchers, let & Context
A Basic Spec
RSpec.describe User do
subject { described_class.new(name: 'Ada') }
describe '#valid?' do
context 'when name is present' do
it { is_expected.to be_valid }
end
context 'when name is missing' do
let(:user) { described_class.new(name: nil) }
it 'is invalid' do
expect(user).not_to be_valid
end
end
end
enddescribe groups examples; it defines one. context is an alias for describe, conventionally used for state/condition groupings. subject + is_expected enables concise one-liners. described_class refers to the class being described without hardcoding its name — stays in sync if the class is renamed.
eq vs. equal, and let's Laziness
expect(value).to eq(other) # value equality (==)
expect(value).to equal(other) # reference identity
let(:user) { User.create!(name: 'Ada') } # lazy — only runs if referenced
before { @user = User.create!(name: 'Ada') } # eager — runs for every exampleSetup & Teardown
before(:each)/after(:each) run per example; before(:all)/after(:all) run once per group. expect syntax (expect(x).to matcher) is the modern default, replacing the older monkey-patched should syntax (x.should matcher).
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free