Stub实例方法使用minitest在第二次调用时返回不同的值

时间:2015-06-16 17:07:06

标签: ruby rspec minitest

我正在对用户的Feed进行分页,并希望模拟我正在使用的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

3 个答案:

答案 0 :(得分:4)

我确定你现在已经弄明白但是......

我不得不使用mocha一个模拟框架来实现这一点。

然后我能够做到这一点:

 Object.any_instance.stubs(:get_value).returns('a','b').then.returns('c')

答案 1 :(得分:1)

尝试向存根提供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从预定义的返回值数组中移位(或弹出)值来利用此行为。

所以在你的情况下,你可以:

  1. 将已定义的second_pagethird_page变量包装在数组中,然后
  2. 将lambda作为#stub的第二个参数传递,该参数在每次调用stubbed方法时都会破坏性地删除并返回数组的第一个元素。
  3. 示例:

    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
    

答案 2 :(得分:0)

我不了解Minitest,但是每次调用方法时,RSpec都可以通过在and_return中指定多个返回值来返回不同的值。

allow(crawler).to receive(:get_next_page).and_return(first_page, second_page, third_page)