Webmock caching responses? Or: How to respond to repeated requests with randomized content

411 views Asked by At

I've tried using a lambda in my custom response:

stub_request(
        :post,
        'http://blah.blah/token'
    ).to_return(
        status: 200,
        body: lambda { |a| '{"token":"' + SecureRandom.hex(20) + '","expires_in":"259200"}' }
    )

Maybe this isn't the correct way to handle dynamic responses, but anyway, webmock seems to execute the lambda exactly once. The request is identical each time, so either:

  1. My asumption that using a lambda would allow me to generate dynamic content on a per-response basis was wrong.
  2. Because the repeated requests are identical, webmock just uses the last response it generated.
1

There are 1 answers

0
womble On

Since this question was written, I strongly suspect that something in Webmock has changed, because the following test passes:

require 'webmock/rspec'
require 'securerandom'
require 'uri'

describe "something" do
   it "happens" do
      s = stub_request(:get, 'example.com/blah').
        to_return(status: 200, body: lambda { |x| SecureRandom.hex(20) })

      expect(Net::HTTP.get(URI('http://example.com/blah')))
        .to_not eq(Net::HTTP.get(URI('http://example.com/blah')))

      expect(s).to have_been_requested.at_least_once
   end
end

Tested with Ruby 2.1.5p273, RSpec 3.3.1, and WebMock 1.21.0.