Tuesday, June 05, 2012

Quality Equality

Trying to compare two arrays for equality without regard to order in a unit test is often very annoying. In Java, it would generally take four or five lines of code to express this in a test, completely obscuring the aspect of the code that I was trying to test. Ruby's Test::Unit turned that comparison into a one-liner, (expected - actual).empty?, a definite improvement but still a bit ugly. I was testing this in RSpec a couple days ago and figured there had to be a better way, and there is: actual.should =~ expected. I probably would have written a custom matcher for this rather than overload =~ if I was designing it myself, but either way, it's a big improvement in test expressiveness and readability.