Class: Minicrest::HasValue

Inherits:
Matcher
  • Object
show all
Defined in:
lib/minicrest/has_value.rb

Overview

Matcher that checks if a hash contains specified values.

Examples:

Single value

has_value(1).matches?({a: 1, b: 2})  # => true

Multiple values

has_value(1, 2).matches?({a: 1, b: 2, c: 3})  # => true

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(*values) ⇒ HasValue

Creates a new has_value matcher.

Parameters:

  • values (Array)

    the values that must be present



15
16
17
18
# File 'lib/minicrest/has_value.rb', line 15

def initialize(*values)
  super()
  @values = values
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



35
36
37
38
39
40
41
# File 'lib/minicrest/has_value.rb', line 35

def description
  if @values.length == 1
    "has value #{@values.first.inspect}"
  else
    "has values #{@values.map(&:inspect).join(', ')}"
  end
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Hash)

    the hash that was checked

Returns:

  • (String)

    failure message listing missing values



47
48
49
50
51
52
53
54
55
# File 'lib/minicrest/has_value.rb', line 47

def failure_message(actual)
  return "expected a Hash, but got #{actual.inspect}" unless actual.respond_to?(:value?)

  missing = @values.reject { |value| actual.value?(value) }
  <<~MSG.chomp
    expected #{format_hash(actual)} to have values #{@values.map(&:inspect).join(', ')}
    missing: #{missing.map(&:inspect).join(', ')}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual hash contains all expected values.

Parameters:

  • actual (Hash)

    the hash to check

Returns:

  • (Boolean)

    true if all values are present



24
25
26
27
28
29
30
# File 'lib/minicrest/has_value.rb', line 24

def matches?(actual)
  return false unless actual.respond_to?(:value?)

  @values.all? { |value| actual.value?(value) }
rescue NoMethodError
  false
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (Hash)

    the hash that was checked

Returns:

  • (String)

    message indicating unexpected value presence



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/minicrest/has_value.rb', line 61

def negated_failure_message(actual)
  if @values.length == 1
    <<~MSG.chomp
      expected #{format_hash(actual)} not to have value #{@values.first.inspect}, but it did
    MSG
  else
    <<~MSG.chomp
      expected #{format_hash(actual)} not to have values #{@values.map(&:inspect).join(', ')}, but it did
    MSG
  end
end