Rails magic — let! method

Mayank Dhanawade
Technogise
Published in
2 min readJan 16, 2023

I was working on writing a spec, I created data using the factory for my test but could not see that data when I ran the test. This is how the data was created initially.

Old code

You see I created data just before the test, but when I ran the test I kept getting the length as 0.

Upon further investigation, I found out that let is lazy evaluated i.e. it will not be evaluated until the method it defines is invoked. Since I didn't call or use item anywhere the data was not created.

To confirm this I added a binding.pry just before the expect and printed the item, when I continued the binding the test passed.

To solve this you can use let! it will force the method’s invocation before each test. The let! is called in sort of a before block, so the item is evaluated and cached before the “it” block runs.

New code

Now the get_items will return the created item.

P.S. This blog is just a small learning I came across while debugging my code, there might be other ways to solve this, but the scope of this blog was just highlighting the let! method.

Thanks for reading!!

--

--

Mayank Dhanawade
Technogise

Developer, travel blogger, wildlife and landscape photographer