Stub instance method different return value on second call using minitest

I am paginating per user and would like to mock the API responses that I am using. The API can return strange results, so I want to make sure that if the API returns elements that I've already seen, stop paging. I used minitest to stub the first time the method is called get_next_page

, but I would like to stub it the second and third time it is called with different values.

Should I be using rSpec? new to ruby ​​...

Here is a snippet

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


source to share


2 answers


I don't know about Minitest, but RSpec can return a different value every time a method is called, setting multiple return values ​​in and_return

.



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

      

0


source


I'm sure you already figured it out, but ...

I had to use mocha dimensional structure to get this to work.



Then I was able to do this:

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

      

0


source







All Articles