Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some code that looks like this:

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

The idea being you can set the app to wait until the server is in a certain state (eg. restart it, then watch it until it's active again)

However, I'm using webmock in the tests, and I can't figure out a way to give a different response the second time.

For example, code like this:

  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 => {})

With the idea being "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"

Is it possible to model multiple calls to the same endpoint with different results in webmock?

like image 697
Peter Souter Avatar asked Oct 18 '15 04:10

Peter Souter


1 Answers

If you pass multiple arguments to #to_return, it will respond each time with the next response, and then just keep returning the last one over and over. For example:

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

When run as rspec <file>, this will print:

ohai
there
there
there
like image 77
womble Avatar answered Oct 23 '22 20:10

womble