如何使用 VCR for Ruby/RSpec 动态生成多个 HTTP 模拟响应?

3 ruby yaml rspec erb vcr

我正在访问一个 API,对于每个请求,盒式 YAML 文件中都有一个记录的请求/响应。但是,请求之间的唯一区别在于id查询参数。

如何缩小 YAML 文件以便为每个请求动态生成 URL?

小智 5

您可以将动态 ERB 磁带与 VCR 一起使用,只需传入选项:erb,该选项可以具有值true或包含要传递到磁带的模板变量的散列:

ids = [0, 1, 2, 3]
VCR.use_cassette('dynamic_generated_requests', :erb => { :ids => ids }) do
  # Make HTTP Requests
end
Run Code Online (Sandbox Code Playgroud)

带有 ERB 的 YAML 文件

您的 YAML 文件将如下所示:

---
http_interactions:
<% ids.each do |id| %>
- request:
    method: post
    uri: https://api.example.com/path/to/rest_api/<%= id %>/method
    body:
      encoding: UTF-8
    headers:
      content-type:
      - application/json
  response:
    status:
      code: 200
      message: OK
    headers:
      cache-control:
      - no-cache, no-store
      content-type:
      - application/json
      connection:
      - Close
    body:
      encoding: UTF-8
      string: '{"status_code": <%= id %>}'
    http_version: '1.1'
  recorded_at: Tue, 15 Jan 2019 16:14:14 GMT
<% end %>
recorded_with: VCR 3.0.0
Run Code Online (Sandbox Code Playgroud)

注意:.yml仍使用文件扩展名,因为 VCR 通过该选项进行 ERB 处理:erb

调试:raw_cassette_bytes

如果你想调试它并确保 YAML 文件看起来不错,你可以使用raw_cassette_bytes方法打印出渲染的 YAML 文件:

puts VCR.current_cassette.send(:raw_cassette_bytes)
Run Code Online (Sandbox Code Playgroud)

在 VCR.use_cassette 块中使用它:

VCR.use_cassette('dynamic_generated_requests', :erb => { :ids => ids }) do
  puts VCR.current_cassette.send(:raw_cassette_bytes)
  # Make HTTP Requests
end
Run Code Online (Sandbox Code Playgroud)