微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VCR gem-我可以将响应数据存储在单独的JSON文件中吗?

如何解决VCR gem-我可以将响应数据存储在单独的JSON文件中吗?

使用VCR gem,将响应保存为YAML卡带文件中的大字符串。像这样:

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

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

解决方法

来自官方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",'Accept-Encoding' => 'identity')
end
,

如果您编写了一个定制的盒式磁带持久器(如此处所述)怎么办?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。