Read more

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

Arne Hartherz
September 30, 2010Software engineer at makandra GmbH

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

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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 => Date.today) }
      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.

Posted by Arne Hartherz to makandra dev (2010-09-30 14:26)