Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

HaveJsonFields matcher

  • Loading branch information...
commit b95b570564b6a33e500310824fff52e9f798ac27 1 parent 26c9e8e
@inossidabile inossidabile authored AlexanderPavlenko committed
View
5 lib/json_spec/matchers.rb
@@ -3,6 +3,7 @@
require "json_spec/matchers/have_json_path"
require "json_spec/matchers/have_json_type"
require "json_spec/matchers/have_json_size"
+require "json_spec/matchers/have_json_fields"
module JsonSpec
module Matchers
@@ -25,6 +26,10 @@ def have_json_type(type)
def have_json_size(size)
JsonSpec::Matchers::HaveJsonSize.new(size)
end
+
+ def have_json_fields(size)
+ JsonSpec::Matchers::HaveJsonFields.new(size)
+ end
end
end
View
35 lib/json_spec/matchers/have_json_fields.rb
@@ -0,0 +1,35 @@
+module JsonSpec
+ module Matchers
+ class HaveJsonFields
+ include JsonSpec::Helpers
+ include JsonSpec::Messages
+
+ def initialize(fields)
+ @fields = fields
+ end
+
+ def matches?(json)
+ @data = parse_json(json, @path)
+ return false unless @data.is_a?(Hash)
+ !@fields.map{|f| @data.has_key?(f)}.include?(false)
+ end
+
+ def at_path(path)
+ @path = path
+ self
+ end
+
+ def failure_message_for_should
+ message_with_path("Expected JSON to contain all of the following fields #{@fields.join(", ")}")
+ end
+
+ def failure_message_for_should_not
+ message_with_path("Expected JSON to not contain any of the following fields #{@fields.join(", ")}")
+ end
+
+ def description
+ message_with_path(%(have JSON fields "#{@fields.join(", ")}"))
+ end
+ end
+ end
+end
View
17 spec/json_spec/matchers/have_json_fields_spec.rb
@@ -0,0 +1,17 @@
+require "spec_helper"
+
+describe JsonSpec::Matchers::HaveJsonFields do
+ it "fails for non-hashes" do
+ %([1,2,3]).should_not have_json_fields([])
+ %(1).should_not have_json_fields([])
+ %("test").should_not have_json_fields([])
+ end
+
+ it "fails for non-complete set of fields" do
+ %({"a": "a", "b": "b"}).should_not have_json_fields(%w(a b c))
+ end
+
+ it "matches complete set of fields" do
+ %({"a": "a", "b": "b", "c": "c"}).should have_json_fields(%w(a b c))
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.