Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

RSpec: Asserting arrays' content without regard to order

Sometimes I want to make assertions about the content of an array when the order of its content is not guaranteed:

nums = [1,2,3].shuffle
nums.length.should == 3
nums.should include 1
nums.should include 2
nums.should include 3

(Of course this is a contrived example, and we could just write nums.sort.should == [1,2,3]. But sometimes we are working with objects that aren’t already sortable.)

I recently found out that RSpec has an array matcher that is specifically intended for this use case, via the =~ operator:

[1,2,3].shuffle.should =~ [1,2,3]
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *

Share This