Created
January 27, 2010 08:59
-
-
Save bronson/287675 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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