我正在对用户的馈送进行分页,并想模拟我正在使用的API的响应。API可能会返回奇怪的结果,因此我希望确保如果API返回我已经看到的项,请停止分页。在第一次调用方法get_next_page时,我使用了minitest来存根,但我想在第二次和第三次使用不同的值调用它时将其存根。
我应该只使用rSpec吗?新手呼叫露比。
以下是代码片段
test "crawler does not paginate if no new items in next page" do
# 1: A, B
# 2: B, D => D
# 3: A => stop
crawler = CrawlJob.new
first_page = [
{"id"=> "item-A"},
{"id"=> "item-B"}
]
second_page = [
{"id"=> "item-B"},
{"id"=> "item-D"}
]
third_page = [{"id"=> "item-A"}]
# can only stub with same second page
# but I want to respond with third page
# the second time get_next_page is called
crawler.stub :get_next_page, second_page do
items, times_paginated = crawler.paginate_feed(first_page)
assert times_paginated == 3
end
end发布于 2016-06-14 07:07:04
我相信你现在已经想明白了,但是...
我不得不使用mocha,一个模拟框架来让它工作。
然后我就可以这样做了:
Object.any_instance.stubs(:get_value).returns('a','b').then.returns('c')发布于 2018-06-15 12:42:10
尝试向存根提供proc或lambda而不是值,例如
return_values = ["returned first", "returned second", "returned third"]
some_object.stub :method_to_stub, proc { return_values.shift }在检查Minitest's source code时,stub方法接受一个值或一个可调用对象作为第二个参数。
您可以通过使用proc或lambda从预定义的返回值数组中移位(或弹出)值来利用此行为。
因此,在您的情况下,您可以:
second_page和third_page变量包装在一个数组中,然后#stub的第二个参数传递,该参数在每次调用存根方法时都会破坏性地移除并返回数组的第一个元素。示例:
return_values = [second_page, third_page]
crawler.stub :get_next_page, ->{ return_values.shift } do
items, times_paginated = crawler.paginate_feed(first_page)
assert times_paginated == 3
end发布于 2015-06-20 05:25:00
我不知道Minitest,但是通过在and_return中指定多个返回值,RSpec能够在每次调用该方法时返回不同的值。
allow(crawler).to receive(:get_next_page).and_return(first_page, second_page, third_page)https://stackoverflow.com/questions/30873890
复制相似问题