rudkovskyi rudkovskyi - 3 months ago 7
Ruby Question

When to use RSpec's let! instead of before?

I have been told that it makes sense to use

let!()
instead of
before(:each)
block. However, I can't see much logic in doing that. Does it actually make any sense to make something like in the example below:

context 'my super context' do
let!(:something) do
Model.create(subject: "Hello", body: "World")
end

it '...' do
# We never call something
# All we want is just to evaluate and create the record
end
end


Keep in mind that you won't call
something
anywhere in the example at all. Technically I don't see much difference between that and this, unless it's actually more strict and easy to understand without documentation just like plain English:

context 'my super context' do
before(:each) do
Model.create(subject: "Hello", body: "World")
end

it '...' do
# We never call something
# All we want is just evaluate and create the record
end
end


Could someone help me to understand the idea behind the rule I was given?
I can understand why you would use
let
instead of
before(:all)
and
before(:each)
with the variable inside. But here it just feels like they just blindly follow the phrase "use a let helper instead of a before block" found somewhere in the blog post.

Thank you very much!

Answer

No, it is not a best practice to always use let! rather than a before block. You're correct:

  • If you want to run a block of code before every example, and you need that code to return a value, use let!.
  • If you want to run a block of code before every example, but you don't need to pass a value from that code directly to your example, use before. (Using let! would mislead the reader into thinking that its value was being used.)

Note that both let! and before blocks should be used sparingly in any case. They create the risk of later test writers adding tests in the same block that don't need the result of the let! or before, making those tests harder to understand and slower.

Comments