Webmock缓存响应?或者:如何用随机内容回应重复的请求



我尝试在自定义响应中使用lambda:

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

也许这不是处理动态响应的正确方式,但无论如何,webmock似乎只执行一次lambda。每次请求都是相同的,所以要么:

  1. 我认为使用lambda可以在每个响应的基础上生成动态内容,这是错误的
  2. 因为重复的请求是相同的,所以webmock只使用它生成的最后一个响应

自从写下这个问题以来,我强烈怀疑Webmock中的某些内容发生了变化,因为以下测试通过了:

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

使用Ruby 2.1.5p273、RSpec 3.3.1和WebMock 1.21.0进行测试。

最新更新