Multiple HTTP requests compatible in one videotape for rspec tests

I have a spec file with an expectation for a controller action to return success.

The action POST api/v1/users/:id/features/block

in the controller makes two HTTP calls to the external API, the only difference is in the body.

I have put two queries and responses in one VCR cassette, but when the cassette is used, only the first query is ever compared and fails when it should match the second, causing the tests to fail.

What I am looking for is a way to match multiple requests, so the controller action completes and returns successfully.

The error I am getting ends up.

describe "POST /api/v1/users/:id/features/block" do
  before(:each) do
    @user = FactoryGirl.create(:user)
    post :block, user_id: @user.id, block: "0"
  end

  it "should return 200 OK" do
    expect(response).to be_success
  end
end

      

Simplified versions of my VCR config and RSpec config:

VCR.configure do |c|
  c.hook_into :webmock
  c.default_cassette_options = {
    match_requests_on: [:method, :uri, :body_regex]
  }
  c.register_request_matcher :body_regex do |request_1, request_2|
    # Match body against regex if cassette body is "--ruby_regex /regexhere/"
    if request_2.body[/^--ruby_regex\s*\//]
      regex = request_2.body.gsub(/^--ruby_regex\s*\//, '').gsub(/\/$/, '')
      request_1.body[/#{regex}/] ? true : false
    else
      true # No regex defined, continue processing
    end
  end
end

RSpec.configure do |c|
  c.around(:each) do |example|
    options = example.metadata[:vcr] || {} 
      name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
      VCR.use_cassette(name, options, &example)
    end
  end
end

      

The generalized version of the cassette used in this comparison that I came across is as follows:

---
http_interactions:
- request:
    method: post
    uri: https://upstream/api
    body:
      string: --ruby_regex /query1.+block/
  response:
    status:
      code: 200
    body:
      string: { "response": "SUCCESS" }
- request:
    method: post
    uri: https://upstream/api
    body:
      string: --ruby_regex /query2.+block/
  response:
    status:
      code: 200
    body:
      string: { "response": "SUCCESS" }
  recorded_at: Fri, 05 Sep 2014 08:26:12 GMT
recorded_with: VCR 2.8.0

      

Error during tests:

An HTTP request has been made that VCR does not know how to handle
...
VCR is using the current cassette: (Correct cassette file path)
...
Under the current configuration VCR can not find a suitable HTTP interaction to replay and is prevented from recording new requests.

      

I dont want to record new requests because the second one overwrites the first one rather than appending the second request to the end of the cassette.

+3


source to share





All Articles