Skip to content

Commit

Permalink
Provide better failure messages for include_json matcher. Addresses i…
Browse files Browse the repository at this point in the history
  • Loading branch information
DanOlson committed Oct 10, 2014
1 parent 50424a8 commit 3cbcc1d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/json_spec/matchers/include_json.rb
Expand Up @@ -5,13 +5,17 @@ class IncludeJson
include JsonSpec::Exclusion
include JsonSpec::Messages

attr_reader :actual_json

def initialize(expected_json = nil)
@expected_json = expected_json
end

def matches?(actual_json)
raise "Expected included JSON not provided" if @expected_json.nil?

self.actual_json = actual_json

actual = parse_json(actual_json, @path)
expected = exclude_keys(parse_json(@expected_json))
case actual
Expand Down Expand Up @@ -43,18 +47,24 @@ def including(*keys)
end

def failure_message
message_with_path("Expected included JSON")
message_with_path("Expected #{actual_json} to include #{@expected_json}")
end
alias :failure_message_for_should :failure_message

def failure_message_when_negated
message_with_path("Expected excluded JSON")
message_with_path("Expected #{actual_json} to exclude #{@expected_json}")
end
alias :failure_message_for_should_not :failure_message_when_negated

def description
message_with_path("include JSON")
end

private

def actual_json=(json)
@actual_json = json
end
end
end
end
16 changes: 16 additions & 0 deletions spec/json_spec/matchers/include_json_spec.rb
Expand Up @@ -71,6 +71,22 @@
matcher.description.should == %(include JSON at path "json/0")
end

it "provides a useful failure message for should" do
actual = %({"ids": [1,2,3]})
expected = %({"ids": [4,5,6]})
matcher = include_json(expected)
matcher.matches?(actual)
matcher.failure_message_for_should.should == "Expected #{actual} to include #{expected}"
end

it "provides a useful failure message for should not" do
actual = %({"ids": [1,2,3]})
expected = actual
matcher = include_json(expected)
matcher.matches?(actual)
matcher.failure_message_for_should_not.should == "Expected #{actual} to exclude #{expected}"
end

it "raises an error when not given expected JSON" do
expect{ %([{"id":1,"two":3}]).should include_json }.to raise_error
end
Expand Down

0 comments on commit 3cbcc1d

Please sign in to comment.