Ruby on rails Webmock缓存响应?或者:如何使用随机内容响应重复请求

Ruby on rails Webmock缓存响应?或者:如何使用随机内容响应重复请求,ruby-on-rails,rspec,tdd,webmock,Ruby On Rails,Rspec,Tdd,Webmock,我已尝试在自定义响应中使用lambda: stub_request( :post, 'http://blah.blah/token' ).to_return( status: 200, body: lambda { |a| '{"token":"' + SecureRandom.hex(20) + '","expires_in":"259200"}' } ) 也许这不是处理动态响应的正确方法,但无论如何,webmo

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

stub_request(
        :post,
        'http://blah.blah/token'
    ).to_return(
        status: 200,
        body: lambda { |a| '{"token":"' + SecureRandom.hex(20) + '","expires_in":"259200"}' }
    )
也许这不是处理动态响应的正确方法,但无论如何,webmock似乎只执行lambda一次。每次请求都是相同的,因此:

  • 我认为使用lambda可以在每个响应的基础上生成动态内容,这是错误的
  • 因为重复的请求是相同的,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进行测试