假设我有一堂课:
class Foo
def process
MyModel.where(id: [1,3,5,7]).each do |my_model|
ExternalService.dispatch(my_modal.id)
end
end
end
我要测试它:
class FooTest < ActiveSupport::TestCase
def process_test
external_service_mock = MiniTest::Mock.new
[1,3,5,7].each do |id|
external_service_mock.expect(:call, true, id)
end
ExternalService.stub(:dispatch, events_mock) do
Foo.new.process
end
external_service_mock.verify
end
end
但是,#expect
强制执行以下调用,与调用#expect
的顺序相同。这对我不利,因为我不确定数据库将以什么顺序返回结果。
如何解决此问题?有没有一种方法可以expect
进行无特定顺序的呼叫?
答案 0 :(得分:2)
尝试使用一套
require 'set'
xs = Set[3,5,7,9]
@cat = Minitest::Mock.new
@cat.expect :meow?, true, [xs]
@cat.meow? 7 # => ok...
@cat.expect :meow?, true, [xs]
@cat.meow? 4 # => boom!
或者,一个不太具体的选项:
鉴于模拟返回的值不是参数值的函数,也许您可以在设置模拟时为参数指定一个类。这是一只期望meow?
被任意整数调用四次的猫的例子。
@cat = Minitest::Mock.new
4.times { @cat.expect(:meow?, true, [Integer]) }
# Yep, I can meow thrice.
@cat.meow? 3 # => true
# Mope, I can't meow a potato number of times.
@cat.meow? "potato" # => MockExpectationError