diff --git a/lib/json_spec/errors.rb b/lib/json_spec/errors.rb index 6c78388..39d23ae 100644 --- a/lib/json_spec/errors.rb +++ b/lib/json_spec/errors.rb @@ -31,4 +31,16 @@ def to_s "No JSON file at #{path}" end end + + class EnumerableExpected < Error + attr_reader :actual_value + + def initialize(actual_value) + @actual_value = actual_value + end + + def to_s + "Enumerable expected, got #{actual_value.inspect}" + end + end end diff --git a/lib/json_spec/matchers/have_json_size.rb b/lib/json_spec/matchers/have_json_size.rb index 53e829b..e9e11c8 100644 --- a/lib/json_spec/matchers/have_json_size.rb +++ b/lib/json_spec/matchers/have_json_size.rb @@ -10,7 +10,8 @@ def initialize(size) def matches?(json) ruby = parse_json(json, @path) - @actual = Enumerable === ruby ? ruby.size : 1 + raise EnumerableExpected.new(ruby) unless Enumerable === ruby + @actual = ruby.size @actual == @expected end diff --git a/spec/json_spec/matchers/have_json_size_spec.rb b/spec/json_spec/matchers/have_json_size_spec.rb index 92ea547..8b9f357 100644 --- a/spec/json_spec/matchers/have_json_size_spec.rb +++ b/spec/json_spec/matchers/have_json_size_spec.rb @@ -46,4 +46,16 @@ matcher.matches?(%({"id":1,"json":["spec"]})) matcher.description.should == %(have JSON size "1" at path "json") end + + it "provides an error when parsing nil" do + matcher = have_json_size(0).at_path("json") + expect { matcher.matches?(%({"id":1,"json":null})) }.to raise_error(JsonSpec::EnumerableExpected, + "Enumerable expected, got nil") + end + + it "provides an error when parsing non-enumerables" do + matcher = have_json_size(0).at_path("json") + expect { matcher.matches?(%({"id":1,"json":12345})) }.to raise_error(JsonSpec::EnumerableExpected, + "Enumerable expected, got 12345") + end end