I love the RSpec let syntax. I especially love using let blocks to declare everything on the planet. However, I was noticing a lot of duplication in my code so I knocked up the below pattern to deal with the issue:

Can’t see this Gist? View it on Github!

The pattern I’m referring to above is declaring and using the vehicle_attributes object to set attributes on an object. The benefits of this pattern is that I’m able to set specific attributes on an object on a per-context basis without having to re-write my call to the factory. The issue that caused me to start using this pattern was having a declaration at the top of the file that was getting overloaded with ‘common’ attributes. My vehicle declaration started to look like:

Can’t see this Gist? View it on Github!

Which worked well enough until I had 4 common attributes on vehicle and 3 other objects that were being created with multiple common attributes as well. My spec file was starting to get ugly.

Even worse, I was declaring vehicle multiple times within describe blocks for other methods.

So, by using the above pattern you can avoid a fair bit of duplication in your specs and keep everything neat and tidy.

Plus, it’ll reduce the amount of code you have to type which gives you more time to browse r/aww