Skip to content

Instantly share code, notes, and snippets.

@bronson
Created January 27, 2010 08:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bronson/287675 to your computer and use it in GitHub Desktop.
Save bronson/287675 to your computer and use it in GitHub Desktop.
# In reply to http://www.ultrasaurus.com/sarahblog/2009/08/ruby-unit-test-frameworks/
# Put this in test_helper.rb to compare two arbitrarily nested structures.
# Usage: compare_objects(o1, o2). Raises an exception if it finds any differences.
# recursivly compare two objects. raise if a difference was found, return if not.
def compare_objects(wanted, actual, path=[])
if wanted.kind_of?(Hash)
raise "Objects differ at #{path.join(".")}: extra keys in wanted: #{(wanted.keys - actual.keys).inspect}" if (wanted.keys - actual.keys).length > 0
raise "Objects differ at #{path.join(".")}: extra keys in actual: #{(actual.keys - wanted.keys).inspect}" if (actual.keys - wanted.keys).length > 0
wanted.keys.sort.each do |key|
compare_objects wanted[key], actual[key], path.dup << key
end
elsif (wanted.kind_of?(Enumerable) && !wanted.kind_of?(String)) && (actual.kind_of?(Enumerable) && !actual.kind_of?(String))
raise "Objects differ at #{path.join(".")}: wanted has #{wanted.length} and actual has #{actual.length} items.\nWANTED=<<#{wanted.inspect}>>\nACTUAL=#{actual.inspect}" if wanted.length != actual.length
(0..wanted.length).each do |i|
compare_objects wanted[i], actual[i], path.dup << "[#{i}]"
end
elsif wanted != actual
raise "Objects differ at #{path.join(".")}:\nWANTED=<<#{wanted.inspect}>>\nACTUAL=<<#{actual.inspect}>>"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment