Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

have_json_fields matcher #25

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/json_spec/matchers.rb
Expand Up @@ -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
Expand All @@ -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

Expand Down
35 changes: 35 additions & 0 deletions 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
17 changes: 17 additions & 0 deletions 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