class Saharspec::Matchers::BeJson

@private

Constants

ANY

Attributes

actual[R]
expected[R]

Public Class Methods

new(expected, **parse_opts) click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 16
def initialize(expected, **parse_opts)
  @expected_matcher = @expected = expected

  # wrap to make be_json('foo' => matcher) work, too
  unless expected == ANY || expected.respond_to?(:matches?)
    @expected_matcher = match(expected)
  end
  @parse_opts = parse_opts
end

Public Instance Methods

description() click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 42
def description
  if @expected == ANY
    'be a valid JSON string'
  else
    expected = @expected.respond_to?(:description) ? @expected.description : @expected
    "be a valid JSON matching (#{expected})"
  end
end
diffable?() click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 38
def diffable?
  true
end
does_not_match?(*args) click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 34
def does_not_match?(*args)
  !matches?(*args)
end
failure_message() click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 51
def failure_message
  failed =
    case
    when @parser_error
      "failed: #{@parser_error}"
    when @expected != ANY
      "was #{@actual}"
    end
  "expected value to #{description} but #{failed}"
end
failure_message_when_negated() click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 62
def failure_message_when_negated
  'expected value not to be parsed as JSON, but succeeded'
end
matches?(json) click to toggle source
# File lib/saharspec/matchers/be_json.rb, line 26
def matches?(json)
  @actual = JSON.parse(json, **@parse_opts)
  @expected_matcher == ANY || @expected_matcher === @actual
rescue JSON::ParserError => e
  @parser_error = e
  false
end