Implement `match` (regex) matcher

This commit is contained in:
Michael Miller 2019-01-19 14:40:14 -07:00
parent 19da933c2f
commit 260e1884ab
2 changed files with 39 additions and 0 deletions

View File

@ -43,5 +43,19 @@ module Spectator::DSL
macro be_a(expected)
::Spectator::Matchers::TypeMatcher({{expected}}).new
end
# Indicates that some value should match another.
# The `=~` operator is used for this check.
# Typically a regular expression is used,
# but any type that has the `=~` operator will work.
#
# Examples:
# ```
# expect("foo").to match(/foo|bar/)
# expect("BAR").to match(/foo|bar/i)
# ```
macro match(expected)
::Spectator::Matchers::RegexMatcher.new({{expected.stringify}}, {{expected}})
end
end
end

View File

@ -0,0 +1,25 @@
require "./value_matcher"
module Spectator::Matchers
# Matcher that tests whether a value matches a regular expression.
# The value is compared with the `=~` operator.
struct RegexMatcher(ExpectedType) < ValueMatcher(ExpectedType)
# Determines whether the matcher is satisfied with the value given to it.
# True is returned if the match was successful, false otherwise.
def match?(partial : Expectations::ValueExpectationPartial(ActualType)) : Bool forall ActualType
!!(partial.actual =~ expected)
end
# Describes the condition that satisfies the matcher.
# This is informational and displayed to the end-user.
def message(partial : Expectations::ValueExpectationPartial(ActualType)) : String forall ActualType
"Expected #{partial.label} to match #{label} (using =~)"
end
# Describes the condition that won't satsify the matcher.
# This is informational and displayed to the end-user.
def negated_message(partial : Expectations::ValueExpectationPartial(ActualType)) : String forall ActualType
"Expected #{partial.label} to not match #{label} (using =~)"
end
end
end