Let or Before?

You’ll notice a lot of specs using before where they really should be using a let.

Rule of thumb:

  • Use before when you need something to happen prior to the test.
  • Use let the way you would usually use a variable, but one that will always return the same value (that’s the memoized bit).

So this:

before { @user = User.new }

would be better as this:

let(:user) { User.new }

I find that using let also makes things more readable. There are times when I’ve used a let and for some reason it hasn’t worked, and then I just use a before instead - whatever works!

I’d be interested to hear more thoughts on this topic.

Added on:
Last updated: