Browse files

Make the JSON type matcher more liberal in the arguments it will accept

  • Loading branch information...
1 parent 5c2111c commit 6ff6acded5b472aac0d669d4073274ef04a70579 @laserlemon laserlemon committed Feb 24, 2012
Showing with 24 additions and 9 deletions.
  1. +2 −2 lib/json_spec/matchers.rb
  2. +1 −1 lib/json_spec/matchers/have_json_size.rb
  3. +21 −6 lib/json_spec/matchers/have_json_type.rb
View
4 lib/json_spec/matchers.rb
@@ -18,8 +18,8 @@ def have_json_path(path)
JsonSpec::Matchers::HaveJsonPath.new(path)
end
- def have_json_type(klass)
- JsonSpec::Matchers::HaveJsonType.new(klass)
+ def have_json_type(type)
+ JsonSpec::Matchers::HaveJsonType.new(type)
end
def have_json_size(size)
View
2 lib/json_spec/matchers/have_json_size.rb
@@ -9,7 +9,7 @@ def initialize(size)
def matches?(json)
ruby = parse_json(json, @path)
- @actual = ruby.is_a?(Enumerable) ? ruby.size : 1
+ @actual = Enumerable === ruby ? ruby.size : 1
@actual == @expected
end
View
27 lib/json_spec/matchers/have_json_type.rb
@@ -3,13 +3,13 @@ module Matchers
class HaveJsonType
include JsonSpec::Helpers
- def initialize(klass)
- @klass = klass
+ def initialize(type)
+ @classes = type_to_classes(type)
end
def matches?(json)
@ruby = parse_json(json, @path)
- @ruby.is_a?(@klass)
+ @classes.any?{|c| c === @ruby }
end
def at_path(path)
@@ -18,22 +18,37 @@ def at_path(path)
end
def failure_message_for_should
- message = "Expected JSON value type to be #{@klass}, got #{@ruby.class}"
+ message = "Expected JSON value type to be #{@classes.join(", ")}, got #{@ruby.class}"
message << %( at path "#{@path}") if @path
message
end
def failure_message_for_should_not
- message = "Expected JSON value type to not be #{@klass}, got #{@ruby.class}"
+ message = "Expected JSON value type to not be #{@classes.join(", ")}, got #{@ruby.class}"
message << %( at path "#{@path}") if @path
message
end
def description
- message = %(have JSON type "#{@klass}")
+ message = %(have JSON type "#{@classes.join(", ")}")
message << %( at path "#{@path}") if @path
message
end
+
+ private
+ def type_to_classes(type)
+ case type
+ when Class then [type]
+ when Array then type.map{|t| type_to_classes(t) }.flatten
+ else
+ case type.to_s.downcase
+ when "boolean" then [TrueClass, FalseClass]
+ when "object" then [Hash]
+ when "nil", "null" then [NilClass]
+ else [Module.const_get(type.to_s.capitalize)]
+ end
+ end
+ end
end
end
end

0 comments on commit 6ff6acd

Please sign in to comment.