1

I have a class Translator which has call to class Connector. Connector class does request to external API, wanted to use VCR to record this API action, then stub instance of Connector class and return VCR response of the API action in call Translator.

class Translator
  def initialize
    @obj = Connector.new().connect
  end

  def format
    # use obj here for some logic
  end
end

class Connector
  def connect
    # http request to external API
  end
end


RSpec.describe Translator, type: :services do
  before do
    allow_any_instance_of(Connector).to receive(:connect).and_return(VCR recorded response)
  end
end

1 Answers1

0

VCR is easy to use, maybe easier than you'd expect and that's why you're having problems.

RSpec.describe Translator, type: :services do
  it do 
    use_vcr_cassette do
      expect(Translator.format).to eq 'Foo'
    end
  end
end

The first time you run the spec - it's will make an HTTP request and save it in a YAML file. The next time you run it - it'll use the recorded response.

It's magic. More info and options: https://relishapp.com/vcr/vcr/v/1-5-0/docs/test-frameworks/usage-with-rspec

Greg
  • 5,862
  • 1
  • 25
  • 52