diff --git a/lib/hash_diff/comparison.rb b/lib/hash_diff/comparison.rb index 44189b7..b6358a0 100644 --- a/lib/hash_diff/comparison.rb +++ b/lib/hash_diff/comparison.rb @@ -67,7 +67,7 @@ def report_difference(key, reporter) if comparable_hash?(key) self.class.new(left[key], right[key]).find_differences(&reporter) elsif comparable_array?(key) - self.class.new(left[key], right[key]).find_differences(&reporter) + self.class.new(left[key], right[key]).find_differences(&reporter) else reporter.call( value_with_default(left, key), @@ -77,7 +77,7 @@ def report_difference(key, reporter) end def value_with_default(obj, key) - obj[key] || NO_VALUE + obj.fetch(key, NO_VALUE) end end end diff --git a/spec/hash_diff/array_comparison_spec.rb b/spec/hash_diff/array_comparison_spec.rb new file mode 100644 index 0000000..a9130f4 --- /dev/null +++ b/spec/hash_diff/array_comparison_spec.rb @@ -0,0 +1,78 @@ +require "spec_helper" + +describe HashDiff::Comparison do + let(:left) { + [ + { + foo: 'bar', + bar: 'foo', + }, + { + nested: { + foo: 'bar', + bar: { + one: 'foo1' + } + }, + }, + { + num: 1, + word: nil + } + ] + } + + def comparison(to_compare) + HashDiff::Comparison.new(left, to_compare) + end + + def right + [ + { + foo: 'bar', + bar: 'foo', + }, + { + nested: { + foo: 'bar', + bar: { + one: 'foo1' + } + }, + }, + { + num: 1, + word: nil + } + ] + end + + describe 'when arrays are the same' do + it 'properly determines equality' do + expect(comparison(right).diff).to be_empty + end + + it 'handles empty arrays' do + expect(HashDiff::Comparison.new([], []).diff).to be_empty + end + end + + describe 'when arrays are different' do + it 'reports arrays as not equal with a different order' do + # move an item from the end to the beginning + right_shuffled = right + popped = right_shuffled.pop + right_shuffled.unshift(popped) + + expect(comparison(right_shuffled).diff).to_not be_empty + end + + it 'should a deep comparison' do + right_with_extra_nested_element = right + right_with_extra_nested_element[1][:nested][:bar][:two] = 'two' + + expect(comparison(right_with_extra_nested_element).diff).to_not be_empty + end + end + +end \ No newline at end of file