Class: Minicrest::Between

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

Overview

Matcher that checks if a value is between a minimum and maximum.

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(min, max, exclusive: false) ⇒ Between

Creates a new between matcher.

Parameters:

  • min (Comparable)

    the minimum value

  • max (Comparable)

    the maximum value

  • exclusive (Boolean) (defaults to: false)

    whether the range is exclusive of min and max



13
14
15
16
17
18
# File 'lib/minicrest/between.rb', line 13

def initialize(min, max, exclusive: false)
  super()
  @min = min
  @max = max
  @exclusive = exclusive
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



39
40
41
42
# File 'lib/minicrest/between.rb', line 39

def description
  range_type = @exclusive ? 'exclusively' : 'inclusively'
  "between #{@min.inspect} and #{@max.inspect} (#{range_type})"
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Object)

    the value that was checked

Returns:

  • (String)

    failure message



48
49
50
51
# File 'lib/minicrest/between.rb', line 48

def failure_message(actual)
  range_type = @exclusive ? 'exclusively' : 'inclusively'
  "expected #{actual.inspect} to be between #{@min.inspect} and #{@max.inspect} (#{range_type})"
end

#matches?(actual) ⇒ Boolean

Checks if actual is between min and max.

Parameters:

  • actual (Object)

    the value to check

Returns:

  • (Boolean)

    true if min <= actual <= max (or < if exclusive)



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/minicrest/between.rb', line 24

def matches?(actual)
  return false unless actual.respond_to?(:>=) && actual.respond_to?(:<=)

  if @exclusive
    actual > @min && actual < @max
  else
    actual >= @min && actual <= @max
  end
rescue ArgumentError, NoMethodError
  false
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (Object)

    the value that was checked

Returns:

  • (String)

    failure message



57
58
59
60
# File 'lib/minicrest/between.rb', line 57

def negated_failure_message(actual)
  range_type = @exclusive ? 'exclusively' : 'inclusively'
  "expected #{actual.inspect} not to be between #{@min.inspect} and #{@max.inspect} (#{range_type}), but it was"
end