RSpec Magic Part 1: Lets
When I first started to use RSpec one of the tricks I was shown was how to extract the set up for each test into a ‘let’. It looks something like this:
let(:variable_name) { statement }
So we can transform a variable declaration in a test block that looks like this:
bicycle = Bicycle.new
into something more generic that lives in the describe block:
let(:bicycle) { Bicycle.new }
And that’s exactly how I used it from there on. You can even do the neat trick
of declaring doubles in a let, along with method stubs:
let(:broken_bicycle) { double :bicycle, broken?: :true }
But let’s try and see what’s going on here. We have a method let, which takes
a symbol as an argument, and then takes a block which it assigns to that
symbol, converted to a variable. Another way of writing this, just to make it
explicit:
let(:bicycle) do
Bicycle.new
end