【问题标题】:VCR gem - Can I store my response data in a separate JSON file?VCR gem - 我可以将我的响应数据存储在单独的 JSON 文件中吗?
【发布时间】:2020-10-29 09:22:40
【问题描述】:

使用 VCR gem,响应在 YAML 磁带文件中保存为一个大字符串。像这样:

 response:
    body:
      string: '{"data":{"salesforceObjects":{"records":[{"student":{"accountId" ...

但是,是否可以将此 JSON 保存在单独的文件中,该文件格式正确且易于阅读?

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec vcr


    【解决方案1】:

    来自官方docs

    VCR.use_cassette('example', :serialize_with => :json) do
      puts response_body_for(:get, "http://localhost:7777/foo", nil, 'Accept-Encoding' => 'identity')
      puts response_body_for(:get, "http://localhost:7777/bar", nil, 'Accept-Encoding' => 'identity')
    end
    

    【讨论】:

    • 这个 sn-p 的哪一部分将 JSON 打印到文件中?我正在使用 seralize_with: :json 但这只是将整个磁带转换为 JSON 而不是 yaml - 响应仍然是一个丑陋的字符串
    【解决方案2】:

    如果您编写了一个自定义盒式磁带持久化器,就像这里记录的那样?

    https://relishapp.com/vcr/vcr/v/2-9-1/docs/cassettes/cassette-persistence

    您可以读取响应正文并将其存储在自定义文件中。然后,在阅读时,将存储的响应正文添加到磁带中。 如果您只是想要一份格式精美的响应副本以供参考,甚至可能不需要这样做。

    以下内容:(未测试)

    class PrettyCassetteBodyPersister
    
      # dunno if content is a string or hash. Might be missing some serialization / deserialization
      # might require extra logic to make it work with multiple request cassettes
    
      def [](name)
        content = YAML.load IO.binread("cassettes/#{name}")
        response_body = JSON.parse IO.binread("cassette_bodies/#{name}")
    
        content['response']['body'] = response_body
        content
      end
    
      def []=(name, content)
        IO.binwrite("cassettes/#{name}", content)
        IO.binwrite("cassette_bodies/#{name}", content['response']['body']
      end
    end
    
    
    VCR.configure do |c|
    
      c.cassette_persisters[:copy_bodies] = PrettyCassetteBodyPersister.new
      c.default_cassette_options = { :persist_with => :copy_bodies }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2013-01-05
      • 2016-04-03
      • 2021-08-03
      • 1970-01-01
      • 2014-12-06
      相关资源
      最近更新 更多