Home When to use RSpec let()?

# When to use RSpec let()?

user6249
1#
user6249 Published in September 20, 2018, 12:45 pm

I tend to use before blocks to set instance variables. I then use those variables across my examples. I recently came upon let(). According to RSpec docs, it is used to

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

How is this different from using instance variables in before blocks? And also when should you use let() vs before()?

• Let blocks are lazily-evaluated, while before blocks run before each example (they are overall slower). Using before blocks depends on personal preference (coding style, mocks/stubs...). Let blocks are usually preferred. You can check a more detailed info about let – Nesha Zoric Feb 8 at 15:58