Skip to content

Commit

Permalink
Array comparison spec
Browse files Browse the repository at this point in the history
  • Loading branch information
iloveitaly committed Aug 23, 2022
1 parent 9f44a9c commit 71c2138
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/hash_diff/comparison.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
Expand Down
78 changes: 78 additions & 0 deletions spec/hash_diff/array_comparison_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 71c2138

Please sign in to comment.