Posted over 11 years ago. Visible to the public.

Taking advantage of RSpec's "let" in before blocks

Inside before :each blocks you can refer to variables that you introduce via let later on.

They do not need to be defined ahead of your before block and can be different for individual sections.

It works just like that:

describe User do describe '#locked?' do before :each do subject.should_receive(:current_plan).and_return plan end context 'when expiring today' do let(:plan) { stub(:expiry => } it 'should be false' do subject.should_not be_locked end end context 'when expired yesterday' do let(:plan) { stub(:expiry => Date.yesterday) } it 'should be true' do subject.should be_locked end end end end

Note this does not work for local variables you set in your it blocks.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Arne Hartherz
Last edit:
over 11 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more