Implement `be_a` matcher

This commit is contained in:
Michael Miller 2019-01-19 14:08:50 -07:00
parent f2569ea3a0
commit 46875d7770
2 changed files with 40 additions and 0 deletions

View File

@ -28,5 +28,20 @@ module Spectator::DSL
macro be(expected)
::Spectator::Matchers::CaseMatcher.new({{expected.stringify}}, {{expected}})
end
# Indicates that some value should be of a specified type.
# The `#is_a?` method is used for this check.
# A type name or type union should be used for `expected`.
#
# Examples:
# ```
# expect("foo").to be_a(String)
#
# x = Random.rand(2) == 0 ? "foobar" : 5
# expect(x).to be_a(Int32 | String)
# ```
macro be_a(expected)
::Spectator::Matchers::TypeMatcher({{expected}}).new({{expected.stringify}}, nil)
end
end
end

View File

@ -0,0 +1,25 @@
require "./value_matcher"
module Spectator::Matchers
# Matcher that tests a value is of a specified type.
# The values are compared with the `#is_a?` method.
struct TypeMatcher(Expected) < ValueMatcher(Nil)
# 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.is_a?(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 be a #{label}"
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 be a #{label}"
end
end
end