Allow have matcher to take multiple values

This commit is contained in:
Michael Miller 2019-02-01 20:27:51 -07:00
parent 6d90966f93
commit 0c4ffdf587
2 changed files with 20 additions and 9 deletions

View file

@ -384,8 +384,15 @@ module Spectator::DSL
# expect(%w[FOO BAR BAZ]).to have(/bar/i) # expect(%w[FOO BAR BAZ]).to have(/bar/i)
# expect([1, 2, 3, :a, :b, :c]).to have(Int32) # expect([1, 2, 3, :a, :b, :c]).to have(Int32)
# ``` # ```
macro have(expected) #
::Spectator::Matchers::HaveMatcher.new({{expected.stringify}}, {{expected}}) # Additionally, multiple arguments can be specified.
# ```
# expect("foobarbaz").to have("foo", "bar")
# expect(%i[a b c]).to have(:a, :b)
# expect(%w[FOO BAR BAZ]).to have(/foo/i, String)
# ```
macro have(*expected)
::Spectator::Matchers::HaveMatcher.new({{expected.splat.stringify}}, {{expected}})
end end
end end
end end

View file

@ -1,7 +1,7 @@
require "./value_matcher" require "./value_matcher"
module Spectator::Matchers module Spectator::Matchers
# Matcher that tests whether a value, such as a `String` or `Array`, matches a value. # Matcher that tests whether a value, such as a `String` or `Array`, matches one or more values.
# For a `String`, the `includes?` method is used. # For a `String`, the `includes?` method is used.
# Otherwise, it expects an `Enumerable` and iterates over each item until `===` is true. # Otherwise, it expects an `Enumerable` and iterates over each item until `===` is true.
struct HaveMatcher(ExpectedType) < ValueMatcher(ExpectedType) struct HaveMatcher(ExpectedType) < ValueMatcher(ExpectedType)
@ -16,19 +16,23 @@ module Spectator::Matchers
end end
end end
# Checks if a `String` matches the expected value. # Checks if a `String` matches the expected values.
# The `includes?` method is used for this check. # The `includes?` method is used for this check.
private def match_string?(actual) private def match_string?(actual)
actual.includes?(expected) expected.all? do |item|
actual.includes?(item)
end
end end
# Checks if an `Enumerable` matches the expected value. # Checks if an `Enumerable` matches the expected values.
# The `===` operator is used on every item. # The `===` operator is used on every item.
private def match_enumerable?(actual) private def match_enumerable?(actual)
actual.each do |item| array = actual.to_a
return true if expected === item expected.all? do |item|
array.any? do |elem|
item === elem
end
end end
false
end end
# Describes the condition that satisfies the matcher. # Describes the condition that satisfies the matcher.