Class: Moarspec::Matchers::BeJson

Inherits:
Object
  • Object
show all
Includes:
RSpec::Matchers, RSpec::Matchers::Composable
Defined in:
lib/moarspec/matchers/be_json.rb

Constant Summary collapse

ANY =
Object.new.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from RSpec::Matchers

#be_json, #be_json_sym, #dont, #eq_multiline, #ret, #send_message

Constructor Details

#initialize(expected, **parse_opts) ⇒ BeJson

Returns a new instance of BeJson.



16
17
18
19
20
21
22
23
24
# File 'lib/moarspec/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

Instance Attribute Details

#actualObject (readonly)

Returns the value of attribute actual.



14
15
16
# File 'lib/moarspec/matchers/be_json.rb', line 14

def actual
  @actual
end

#expectedObject (readonly)

Returns the value of attribute expected.



14
15
16
# File 'lib/moarspec/matchers/be_json.rb', line 14

def expected
  @expected
end

Instance Method Details

#descriptionObject



42
43
44
45
46
47
48
49
# File 'lib/moarspec/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?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/moarspec/matchers/be_json.rb', line 38

def diffable?
  true
end

#does_not_match?(*args) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/moarspec/matchers/be_json.rb', line 34

def does_not_match?(*args)
  !matches?(*args)
end

#failure_messageObject



51
52
53
54
55
56
57
58
59
60
# File 'lib/moarspec/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_negatedObject



62
63
64
# File 'lib/moarspec/matchers/be_json.rb', line 62

def failure_message_when_negated
  'expected value not to be parsed as JSON, but succeeded'
end

#matches?(json) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
# File 'lib/moarspec/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