【问题标题】:how do I dynamically generate multiple HTTP mock responses with VCR for Ruby/RSpec?如何使用 VCR for Ruby/RSpec 动态生成多个 HTTP 模拟响应?
【发布时间】:2019-01-15 17:02:01
【问题描述】:

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

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

【问题讨论】:

    标签: ruby rspec yaml erb vcr


    【解决方案1】:

    您可以将Dynamic ERB Cassettes 与VCR 一起使用,您只需传入:erb 选项,该选项的值可以是true 或包含要传递给磁带的模板变量的哈希:

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

    带有 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
    

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

    调试:raw_cassette_bytes

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

    puts VCR.current_cassette.send(:raw_cassette_bytes)
    

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2017-10-09
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2013-04-13
      相关资源
      最近更新 更多