Did you know about this sweat little trick to test arrays in RSpec?

This article is quite old.Time flies when you're having fun. I've been writing for my blog for a long time. Stuff changes fast, especially in the Ruby world. That's why I've put this warning on old posts. The article might still be valid, though.

RSpec Array Matcher

If you're testing arrays a lot, like ActiveRecord's (named) scopes, you should know the following RSpec matcher: =~. It doesn't care about sorting and it gives you all the output you need when the spec fails. Here is an example:

describe "array matching" do

  it "should pass" do
    [ 1, 2, 3 ].should =~ [ 2, 3, 1 ]
  end

  it "should fail" do
    [ 1, 2, 3 ].should =~ [ 4, 2, 3 ]
  end

end

Note: There is no inverse (should_not) version of this matcher.

comments powered byDisqus