I just started writing RSpec tests, and I came across thoughtbot’s Style Guide, which recommends against let, let!, before and subject (among others).
I’ve also read similar suggestions in a few other places (including the old RSpec docs warning about before(:all)), but I can’t seem to find the actual argument against them.
So the question is:
Why shouldn’t I be using those methods in my tests? What is the better approach?
Interesting question; something that I want to know more about as well…. So dug in a bit, and here is what I uncovered:
Thoughtbot style guide dictum about
let, etc.In an earlier version of the style guide, there’s more to that statement:
Avoid its, let, let!, specify, subject, and other DSLs. Prefer explicitness and consistency.
ThoughtBot folks made a post on let name let’s not. See also the link to the Github Commit Comment conversation
On one of their recent podcasts Joe Ferris, the CTO of ThoughtBot, explains why it’s not a good idea to use
letandsubject. Check out the podcast titled Something Else Was Smellier from the 27m37s mark onwards for the next 5 minutes.Testing Anti-pattern ‘Mystery Guest’ which is dealt with in detail in an older ThoughtBot blogpost is the main reason for why not to use
letand its cousins.To summarize my understanding of all the above very succinctly:
before(:all)
The argument against using
before(:all)is straight-forward. As explained in the old rspec documentation:before(:all) gets executed only once at the start of the ExampleGroup. As such there is a potential to inadvertently introduce dependencies between the Examples. Thoughtbot’s assertion about the tests not being easy to understand applies to this as well.
In conclusion, the advise for writing better specs seems to be: