Search code examples
ruby-on-railsrspecvcr

Why are records not being stored to the db when testing with VCR?


I have an interactor foo with method perform on it which makes an API call, and records the response through ActiveRecord. It works fine. I have a spec for it that triggers the method with FactoryBot data, then checks the db for the expected records. This also works fine. However, when I wrap the call in a VCR.use_cassette, the call is made (and resulting cassette created), but the db records don't seem to be written. What am I missing?

spec looks like this:

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 method looks roughly like this:

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 should be created by the call to perform. Without VCR it is.


Solution

  • For the curious, there was in fact nothing wrong with VCR. I was storing items with a fixed timestamp, and then reading them with a dynamic one that didn't overlap. Full pebkac.