Saturday, April 10, 2010

Showing hash differences in Ruby tests

Today I was writing some tests for a Rails plugin I'm working on. The test had to compare a hash output by a method with an expected hash.

This is reasonably standard stuff - when assertion_equal failed it printed out the expected and provided data. The problem in my case was that the hashes have about 50 elements, and I only want the difference to be shown in the test output.

I knocked up this function to solve the problem, and included it in my test class:def assert_hashes_equal(expected, actual, message=nil)full_message = build_message(message, "Hashes were not equal, diff was:\n.\n", expected.diff(actual))assert_block(full_message) { expected == actual }end