【问题标题】:Webmock caching responses? Or: How to respond to repeated requests with randomized contentWebmock 缓存响应?或者:如何使用随机内容响应重复请求
【发布时间】:2013-12-17 20:02:51
【问题描述】:
我尝试在自定义响应中使用 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 只使用它生成的最后一个响应。
【问题讨论】:
标签:
ruby-on-rails
rspec
tdd
webmock
【解决方案1】:
自从写了这个问题,我强烈怀疑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 测试。