一个VCR盒中可匹配多个HTTP请求以进行rspec测试

 大苏打的苏打水 发布于 2022-12-23 11:19

我有一个规范文件,期望控制器操作将返回成功。

POST api/v1/users/:id/features/block控制器中的操作在外部API上调用了两个HTTP调用,唯一的不同在于主体。

我已将两个请求和响应放在同一VCR盒式磁带中,但是当使用盒式磁带时,只有第一个请求与之比较,而当第二个请求与第二个匹配时就会失败,从而导致测试失败。

我正在寻找一种使多个请求匹配的方法,以便控制器操作完成并成功返回。

我得到的错误是在结尾。

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

我的VCR配置和RSpec配置的简化版本如下:

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

我在比较中遇到的卡带的摘要版本是:

---
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

测试期间发生错误:

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.

我不想记录新的请求,因为第二个请求会覆盖第一个请求,而不是将第二个请求添加到录像带的末尾。

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有