Tag Archives: rspec

RSpec let! and before

‘let’ in rspec allows you to define objects and methods to an instance method. Official docs:

Use let to define a memoized helper method. The value will be cached across
multiple calls in the same example but not across examples.

‘let!’ allows you to define an object that is run in a `before` hook. I was curious to the order of execution of ‘before’ hooks and let, so I ran a simple test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
context 'when testing before' do
  before :all do
    p 'before :all invoked'
  end
 
  before do
    p 'before :each invoked'
  end
 
  let!(:test) { p 'let! invoked' }
 
  it 'prints debug statements' do
  end
end

The results were:

"before :all invoked"
"before :each invoked"
"let! invoked"

So, it seems the before hooks are run BEFORE the let! hooks. This is useful info to note if you need the let! method to be run before the before block, you’ll need to call it manually yourself like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
context 'when testing before' do
  before :all do
    p 'before :all invoked'
  end
 
  before do
    test
    p 'before :each invoked'
  end
 
  let!(:test) { p 'let! invoked' }
 
  it 'prints debug statements' do
  end
end

and we get:

"before :all invoked"
"let! invoked"
"before :each invoked"