Thursday, 11 December 2014

12 Tips of Christmas - 1 Use .map with Rspec

In the Christmas spirit of giving, I wanted to share with you 12 months worth of little tidbits that can help your Rails code. These are all little tips that I have been finding incredibly useful this year, and I'll be releasing one each day right up until Christmas Eve. 

1. Use map when comparing arrays in Rspec

Often when writing tests for a scope, or array equality, we'll end up with something like:
it { expect( match_array([user_active, user_guest_active]) }
Of course, when that test fails, we end up with a lot of noise, as the output will give us the object in full. 
An easier way, is to use map to actually get out the information we're interested in:
it { expect( match_array([user_active, user_guest].map(&:first_name) }
This way, when we get our output back on our failing tests, it's much easier to determine what is actually wrong with our test as well as make it that much more obvious to the reader what they're looking for in return.

No comments:

Post a Comment