Skip to content

Commit 794b747

Browse files
committed
Merge pull request #82 from eluns/master
Raise error when checking a size of a json ruby value of nil
2 parents 104b248 + acfa179 commit 794b747

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

lib/json_spec/errors.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,16 @@ def to_s
3131
"No JSON file at #{path}"
3232
end
3333
end
34+
35+
class EnumerableExpected < Error
36+
attr_reader :actual_value
37+
38+
def initialize(actual_value)
39+
@actual_value = actual_value
40+
end
41+
42+
def to_s
43+
"Enumerable expected, got #{actual_value.inspect}"
44+
end
45+
end
3446
end

lib/json_spec/matchers/have_json_size.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ def initialize(size)
1010

1111
def matches?(json)
1212
ruby = parse_json(json, @path)
13-
@actual = Enumerable === ruby ? ruby.size : 1
13+
raise EnumerableExpected.new(ruby) unless Enumerable === ruby
14+
@actual = ruby.size
1415
@actual == @expected
1516
end
1617

spec/json_spec/matchers/have_json_size_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,16 @@
4646
matcher.matches?(%({"id":1,"json":["spec"]}))
4747
matcher.description.should == %(have JSON size "1" at path "json")
4848
end
49+
50+
it "provides an error when parsing nil" do
51+
matcher = have_json_size(0).at_path("json")
52+
expect { matcher.matches?(%({"id":1,"json":null})) }.to raise_error(JsonSpec::EnumerableExpected,
53+
"Enumerable expected, got nil")
54+
end
55+
56+
it "provides an error when parsing non-enumerables" do
57+
matcher = have_json_size(0).at_path("json")
58+
expect { matcher.matches?(%({"id":1,"json":12345})) }.to raise_error(JsonSpec::EnumerableExpected,
59+
"Enumerable expected, got 12345")
60+
end
4961
end

0 commit comments

Comments
 (0)