Use ranges to specify call count

This commit is contained in:
Michael Miller 2019-11-03 13:59:38 -07:00
parent 2048267eef
commit dabd3a7658

View file

@ -3,7 +3,9 @@ require "./standard_matcher"
module Spectator::Matchers module Spectator::Matchers
struct ReceiveMatcher < StandardMatcher struct ReceiveMatcher < StandardMatcher
def initialize(@expected : TestExpression(Symbol), @count : Int32? = nil) alias Range = ::Range(Int32, Int32) | ::Range(Nil, Int32) | ::Range(Int32, Nil)
def initialize(@expected : TestExpression(Symbol), @range : Range? = nil)
end end
def description : String def description : String
@ -13,8 +15,8 @@ module Spectator::Matchers
def match?(actual : TestExpression(T)) : Bool forall T def match?(actual : TestExpression(T)) : Bool forall T
double = actual.value.as(Mocks::Double) double = actual.value.as(Mocks::Double)
calls = double.spectator_stub_calls(@expected.value) calls = double.spectator_stub_calls(@expected.value)
if (count = @count) if (range = @range)
count == calls.size range.includes?(calls.size)
else else
!calls.empty? !calls.empty?
end end
@ -27,10 +29,39 @@ module Spectator::Matchers
def values(actual : TestExpression(T)) forall T def values(actual : TestExpression(T)) forall T
double = actual.value.as(Mocks::Double) double = actual.value.as(Mocks::Double)
calls = double.spectator_stub_calls(@expected.value) calls = double.spectator_stub_calls(@expected.value)
range = @range
{ {
expected: "#{@count ? "#{@count} time(s)" : "At least once"} with any arguments", expected: "#{range ? "#{humanize_range(range)} time(s)" : "At least once"} with any arguments",
received: "#{calls.size} time(s) with any arguments", received: "#{calls.size} time(s) with any arguments",
} }
end end
def once
ReceiveMatcher.new(@expected, (1..1))
end
def twice
ReceiveMatcher.new(@expected, (2..2))
end
def humanize_range(range : Range)
if (min = range.begin)
if (max = range.end)
if min == max
min
else
"#{min} to #{max}"
end
else
"At least #{min}"
end
else
if (max = range.end)
"At most #{max}"
else
raise "Unexpected endless range"
end
end
end
end end
end end