在 webmock 中对同一个端点的多次调用具有不同的结果?

Multiple calls to the same endpoint with different results in webmock?

我有一些代码如下所示:

while response.droplet.status != env["user_droplet_desired_state"] do
   sleep 2
   response = ocean.droplet.show env["droplet_id"]
   say ".", nil, false
end

您可以将应用程序设置为等到服务器处于特定状态(例如,重新启动它,然后观察它直到它再次处于活动状态)

但是,我在测试中使用了 webmock,我想不出一种方法来第二次给出不同的响应。

例如,代码如下:

  stub_request(:get, "https://api.digitalocean.com/v2/droplets/6918990?per_page=200").
     with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization'=>'Bearer foo', 'Content-Type'=>'application/json', 'User-Agent'=>'Faraday v0.9.2'}).
     to_return(:status => 200, :body => fixture('show_droplet_inactive'), :headers => {})

  stub_request(:get, "https://api.digitalocean.com/v2/droplets/6918990?per_page=200").
     with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization'=>'Bearer foo', 'Content-Type'=>'application/json', 'User-Agent'=>'Faraday v0.9.2'}).
     to_return(:status => 200, :body => fixture('show_droplet'), :headers => {})

想法是"First time mark as in-active so the loop goes through one-time, then mark as active afterwards"

The documentation says that stubs are just done as "Last one found will work":

Always the last declared stub matching the request will be applied i.e:

stub_request(:get, "www.example.com").to_return(:body => "abc")

stub_request(:get, "www.example.com").to_return(:body => "def")

Net::HTTP.get('www.example.com', '/') # ====> "def"

是否可以在 webmock 中模拟对同一端点的多次调用,但结果不同?

如果您将多个参数传递给 #to_return,它每次都会响应下一个响应,然后一遍又一遍地返回最后一个。例如:

require 'webmock/rspec'
require 'uri'

describe "something" do
   it "happens" do
      stub_request(:get, 'example.com/blah').
        to_return({status: 200, body: 'ohai'}, {status: 200, body: 'there'})

      puts Net::HTTP.get(URI('http://example.com/blah'))
      puts Net::HTTP.get(URI('http://example.com/blah'))
      puts Net::HTTP.get(URI('http://example.com/blah'))
      puts Net::HTTP.get(URI('http://example.com/blah'))
   end
end

当 运行 为 rspec <file> 时,这将打印:

ohai
there
there
there