Method: RSpec::ComposableJSONMatchers#be_json

Defined in:
lib/rspec/composable_json_matchers.rb

#be_json(matcher_or_json_value) ⇒ Object

Passes if actual string can be decoded as JSON and the decoded value passes the given matcher. When a JSON value is given, it's handled as be_json matching(value) (matching is an alias of the match matcher).

Examples:

expect('{ "foo": 1, "bar": 2 }').to be_json(foo: 1, bar: 2)
expect('{ "foo": 1, "bar": 2 }').to be_json(foo: 1, bar: a_kind_of(Integer))
expect('{ "foo": 1, "bar": 2 }').to be_json matching(foo: 1, bar: 2)
expect('{ "foo": 1, "bar": 2 }').to be_json including(foo: 1)
expect('{ "foo": 1, "bar": 2 }').to be_json a_kind_of(Hash)

Parameters:

  • matcher_or_json_value

    [#matches?, Hash, Array, Numeric, String, TrueClass, FalseClass, NilClass] a matcher object or a JSON value



99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/rspec/composable_json_matchers.rb', line 99

def be_json(matcher_or_json_value)
  if ComposableJSONMatchers.matcher?(matcher_or_json_value)
    BeJSON.new(matcher_or_json_value, ComposableJSONMatchers.configuration)
  elsif ComposableJSONMatchers.json_value?(matcher_or_json_value)
    matcher = matching(matcher_or_json_value)
    BeJSON.new(matcher, ComposableJSONMatchers.configuration)
  else
    raise ArgumentError, 'You must pass a matcher or a JSON value ' \
                         '(hash, array, numeric, string, true, false, or nil) ' \
                         'to `be_json` matcher.'
  end
end