Class: JSONSpectacular::Matcher

Inherits:
Object
  • Object
show all
Includes:
DiffDescriptions
Defined in:
lib/json_spectacular/matcher.rb

Overview

Backing class for the eql_json RSpec matcher. Used for matching Ruby representations of JSON response bodies. Provides clear diff representations for simple and complex or nested JSON objects, highlighting only the values that are different, and where they are in the larger JSON object.

Expected to be used as part of a RSpec test suite and with RSpec#json_response.

See Also:

Author:

  • Aleck Greenham

Instance Method Summary collapse

Methods included from DiffDescriptions

included

Constructor Details

#initialize(expected) ⇒ JSONSpectacular::Matcher

Creates a new JSONSpectacular::Matcher object.

Parameters:

  • expected (String, Number, Boolean, Array, Hash)

    The expected value that will be compared with the actual value

See Also:



28
29
30
31
32
# File 'lib/json_spectacular/matcher.rb', line 28

def initialize(expected)
  @expected = expected
  @message = ''
  @reported_differences = {}
end

Instance Method Details

#diffable?false

Declares that RSpec should not attempt to diff the actual and expected values to put in the failure message. This class takes care of diffing and presenting the differences, itself.

Returns:

  • (false)

    Always false



38
39
40
# File 'lib/json_spectacular/matcher.rb', line 38

def diffable?
  false
end

#failure_messageString

Message to display to StdOut by RSpec if the equality check fails. Includes a complete serialisation of expected and actual values and is then followed by a description of only the (possibly deeply nested) attributes that are different

Returns:

  • (String)

    message full failure message with explanation of why actual failed the equality check with expected



57
58
59
60
61
62
63
64
65
# File 'lib/json_spectacular/matcher.rb', line 57

def failure_message
  @message += "Expected: #{@expected}\n\n"
  @message += "Actual: #{@actual}\n\n"
  @message += "Differences\n\n"

  add_diff_to_message(@actual, @expected)

  @message
end

#matches?(actual) ⇒ Boolean

Whether the actual value and the expected value are considered equal.

Parameters:

  • actual (String, Number, Boolean, Array, Hash)

    The value to be compared to expected for equality

Returns:

  • (Boolean)

    True when actual equals expected.



46
47
48
49
# File 'lib/json_spectacular/matcher.rb', line 46

def matches?(actual)
  @actual = actual
  @expected.eql?(@actual)
end