0

Using VCR in my rspec test and everything is working fine. But I wanna improve the code quality as I have used multiple times same code VCR.use_cassette in my test.

Here is the test:-

context 'when request authenticated and Params are valid' do
  it 'results should have success' do
    VCR.use_cassette('test_service') do
      post '/rates', headers: auth_headers, params: params
      expect(response.status).to be(200)
    end
  end

  it 'results should have nominal nominal_interest_rate' do
    VCR.use_cassette('test_service') do
      post '/rates', headers: auth_headers, params: params
      expect(response.body).to include('rate')
      expect(JSON.parse(response.body).class).to eq(Hash)
    end
  end

  it 'results should have nominal discount' do
    VCR.use_cassette('test_service') do
      post '/rates', headers: auth_headers, params: params
      expect(response.body).to include('discount')
    end
  end
end

As in above code I have used VCR.use_cassette multiple times. I want to make this as a common block and use it multiple time I need. How can I do that?

Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133

1 Answers1

0

According to the Docs you can use "RSpec metadata" and pass the cassette to the example or example group as an argument ({vcr: 'cassette name'}) e.g.

"spec/spec_helper.rb"

VCR.configure do |c| 
  c.configure_rspec_metadata!
end

And then

"spec/your_spec.rb"

context 'when request authenticated and Params are valid', vcr: 'test_service' do
  before(:each) do 
    post '/rates', headers: auth_headers, params: params
  end
  it 'results should have success' do
    expect(response.status).to be(200)
  end

  it 'results should have nominal nominal_interest_rate' do
    expect(response.body).to include('rate')
    expect(JSON.parse(response.body).class).to eq(Hash)
  end

  it 'results should have nominal discount' do
    expect(response.body).to include('discount')
  end
end
engineersmnky
  • 25,495
  • 2
  • 36
  • 52