首页 > 解决方案 > 使用 VCR 进行测试时,为什么没有将记录存储到数据库中?

问题描述

我有一个foo带有方法的交互器,perform它进行 API 调用,并通过 ActiveRecord 记录响应。它工作正常。我有一个规范,它使用 FactoryBot 数据触发该方法,然后检查数据库中的预期记录。这也很好用。但是,当我将调用包装在 a 中时VCR.use_cassette,会进行调用(并创建结果磁带),但似乎没有写入 db 记录。我错过了什么?

规格看起来像这样:

it 'should do a thing' do
  bar = FactoryGirl.create(:bar)

  VCR.use_cassette('foo/cassette') do
    MyInteractor.perform(bar)
  end

  record = BarRecord.find_by(bar_id: bar.id)
  expect(record.status.to_sym).to be(:success)
end

perform方法大致如下:

def perform(bar)
  uri = URI.parse("<url>")
  req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
  req.basic_auth Settings.username, Settings.password
  req['Accept'] = 'Application/json'
  req.body = post_params.to_json

  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  res = https.request(req)

  record = BarRecord.new(bar_id: bar.id)
  record.status = JSON.parse(res.body)["status"]
  record.save!
  record
end

BarRecord应该通过调用来创建perform。没有录像机它是。

标签: ruby-on-railsrspecvcr

解决方案


对于好奇的人来说,实际上 VCR 并没有什么问题。我正在存储具有固定时间戳的项目,然后使用不重叠的动态时间戳读取它们。完整的pebkac。


推荐阅读