Class: Minicrest::MatchesPattern

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

Overview

Matcher that checks if a string matches a regular expression.

Examples:

Basic usage

matches_pattern(/\d+/).matches?("hello123")  # => true
matches_pattern(/\d+/).matches?("hello")     # => false

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(pattern) ⇒ MatchesPattern

Creates a new pattern matcher.

Parameters:

  • pattern (Regexp)

    the expected pattern



13
14
15
16
# File 'lib/minicrest/matches_pattern.rb', line 13

def initialize(pattern)
  super()
  @pattern = pattern
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description of expected pattern



33
34
35
# File 'lib/minicrest/matches_pattern.rb', line 33

def description
  "a string matching #{@pattern.inspect}"
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (String)

    the string that was checked

Returns:

  • (String)

    message showing expected pattern



41
42
43
44
45
46
# File 'lib/minicrest/matches_pattern.rb', line 41

def failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect}
          to match pattern #{@pattern.inspect}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual matches the expected pattern.

Parameters:

  • actual (String)

    the string to check

Returns:

  • (Boolean)

    true if actual matches pattern



22
23
24
25
26
27
28
# File 'lib/minicrest/matches_pattern.rb', line 22

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

  @pattern.match?(actual)
rescue TypeError
  false
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (String)

    the string that was checked

Returns:

  • (String)

    message indicating unexpected pattern match



52
53
54
55
56
57
58
# File 'lib/minicrest/matches_pattern.rb', line 52

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect}
          not to match pattern #{@pattern.inspect}
    but it does
  MSG
end