Skip to content

Commit 71c2138

Browse files
committed
Array comparison spec
1 parent 9f44a9c commit 71c2138

File tree

2 files changed

+80
-2
lines changed

2 files changed

+80
-2
lines changed

lib/hash_diff/comparison.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def report_difference(key, reporter)
6767
if comparable_hash?(key)
6868
self.class.new(left[key], right[key]).find_differences(&reporter)
6969
elsif comparable_array?(key)
70-
self.class.new(left[key], right[key]).find_differences(&reporter)
70+
self.class.new(left[key], right[key]).find_differences(&reporter)
7171
else
7272
reporter.call(
7373
value_with_default(left, key),
@@ -77,7 +77,7 @@ def report_difference(key, reporter)
7777
end
7878

7979
def value_with_default(obj, key)
80-
obj[key] || NO_VALUE
80+
obj.fetch(key, NO_VALUE)
8181
end
8282
end
8383
end
+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
require "spec_helper"
2+
3+
describe HashDiff::Comparison do
4+
let(:left) {
5+
[
6+
{
7+
foo: 'bar',
8+
bar: 'foo',
9+
},
10+
{
11+
nested: {
12+
foo: 'bar',
13+
bar: {
14+
one: 'foo1'
15+
}
16+
},
17+
},
18+
{
19+
num: 1,
20+
word: nil
21+
}
22+
]
23+
}
24+
25+
def comparison(to_compare)
26+
HashDiff::Comparison.new(left, to_compare)
27+
end
28+
29+
def right
30+
[
31+
{
32+
foo: 'bar',
33+
bar: 'foo',
34+
},
35+
{
36+
nested: {
37+
foo: 'bar',
38+
bar: {
39+
one: 'foo1'
40+
}
41+
},
42+
},
43+
{
44+
num: 1,
45+
word: nil
46+
}
47+
]
48+
end
49+
50+
describe 'when arrays are the same' do
51+
it 'properly determines equality' do
52+
expect(comparison(right).diff).to be_empty
53+
end
54+
55+
it 'handles empty arrays' do
56+
expect(HashDiff::Comparison.new([], []).diff).to be_empty
57+
end
58+
end
59+
60+
describe 'when arrays are different' do
61+
it 'reports arrays as not equal with a different order' do
62+
# move an item from the end to the beginning
63+
right_shuffled = right
64+
popped = right_shuffled.pop
65+
right_shuffled.unshift(popped)
66+
67+
expect(comparison(right_shuffled).diff).to_not be_empty
68+
end
69+
70+
it 'should a deep comparison' do
71+
right_with_extra_nested_element = right
72+
right_with_extra_nested_element[1][:nested][:bar][:two] = 'two'
73+
74+
expect(comparison(right_with_extra_nested_element).diff).to_not be_empty
75+
end
76+
end
77+
78+
end

0 commit comments

Comments
 (0)