使用VCR-gem,响应被保存为YAML盒式文件中的一个大字符串。像这样:
response:
body:
string: '{"data":{"salesforceObjects":{"records":[{"student":{"accountId" ...
但是,是否可以将这个JSON保存在一个单独的文件中,该文件格式正确,更易于阅读?
来自官方文档:
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
如果您编写了一个自定义的盒式磁带持久器,如本文所述,该怎么办?
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