Why are let and let! bad practice?

Hi All,

I was just reading rspec cheat sheet. One thing it mentioned was be careful with let/let!. I read the description but still don’t get why. Can anyone give an example? Alternatively, what should I do? Should I setup all objects in the factories file?

Frank

Please have a look at this post from our blog: Let's Not

Thanks. This post is really helpful. My biggest take-away is one should make setup logic clear within each test so that we know exactly what assumptions we are making (addressing the mystery guest problem).

Along these same lines, a mentoring subscriber asked me:

One of the rails developers here is encouraging me to use things like let and subject in rspec. In your guide you also say to avoid those.

I was looking around at some tests in the thoughtbot repo to get some ideas for setting up my tests and saw this one which is using let and subject
https://github.com/thoughtbot/clearance/blob/master/spec/models/bcrypt_spec.rb

are you changing your stance on let and subject?

The simple answer is no, we are not changing our stance on this. Actually, our stance changed to this a while ago.

If you go the blame view of that file:

https://github.com/thoughtbot/clearance/blame/master/spec/models/bcrypt_spec.rb

You can see that those let lines were written in July of 2012.

As we note in our guides

Don’t rewrite existing code to follow this guide.

If somewhere were to significantly touch this spec (which as you can see from the blame, hasn’t really happened), they would have license to rewrite the spec for the code they were touching to match the new style, but we wouldn’t change code to match a new style that we aren’t touching.

I hope that helps!
-Chad

1 Like