Module: Decoding::MatcherHelpers

Defined in:
lib/decoding/matcher_helpers.rb

Overview

Shared logic for the matchers that describe decoding, loaded along with them by require "decoding/rspec".

Decoders report failures as Failure values, but decode renders those into strings, so matchers have to understand both.

Instance Method Summary collapse

Instance Method Details

#describe_failure(result) ⇒ Array(String, Array)

Split the error value of a result into its message and the path it occurred at, with the outermost path segment first.

Parameters:

Returns:

  • (Array(String, Array))


15
16
17
18
19
20
21
# File 'lib/decoding/matcher_helpers.rb', line 15

def describe_failure(result)
  error = result.unwrap_err(nil)
  return [error.msg, error.path.reverse] if error.is_a?(Decoding::Failure)

  match = error.to_s.match(/\AError at \.(?<path>.+?): (?<msg>.*)\z/m)
  match ? [match[:msg], match[:path].split(".")] : [error.to_s, []]
end

#expected_path ⇒ Array

The path set by the at chain, if any.

Returns:

  • (Array)


30
# File 'lib/decoding/matcher_helpers.rb', line 30

def expected_path = @expected_path ||= []

#matches_value?(expected, actual) ⇒ Boolean

Compare a decoded value to what the example expects. Values are compared strictly, so that a decoder returning a value of the wrong type is not mistaken for a success, unless the example expects a matcher rather than a value.

Parameters:

  • expected (Object)
  • actual (Object)

Returns:

  • (Boolean)


44
45
46
47
48
# File 'lib/decoding/matcher_helpers.rb', line 44

def matches_value?(expected, actual)
  return values_match?(expected, actual) if RSpec::Support.is_a_matcher?(expected)

  actual.eql?(expected)
end

#path_matches?(path) ⇒ Boolean

Parameters:

  • path (Array)

Returns:

  • (Boolean)


34
# File 'lib/decoding/matcher_helpers.rb', line 34

def path_matches?(path) = path.map(&:to_s) == expected_path.map(&:to_s)

#render_path(path) ⇒ String

Parameters:

  • path (Array)

Returns:

  • (String)


25
# File 'lib/decoding/matcher_helpers.rb', line 25

def render_path(path) = path.empty? ? "" : " at .#{path.join(".")}"