某些特定 RSpec 测试的自定义 VCR 请求匹配选项 [英] Custom VCR request matching options for some specific RSpec tests

查看:50
本文介绍了某些特定 RSpec 测试的自定义 VCR 请求匹配选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 项目中有一堆 RSpec 测试,用于测试对外部 REST API 的 HTTP 调用,并使用 VCR 磁带记录请求和响应.目前我的 VCR 配置如下:

I have a bunch of RSpec tests in my Rails project that test HTTP calls to external REST API and use VCR cassettes to record requests and respondes. Currently my VCR configuration is the following:

VCR.configure do |c|
  c.cassette_library_dir = 'spec/vcr_cassettes'
  c.hook_into :webmock
  c.configure_rspec_metadata!
end

所以请求匹配规则只匹配 HTTP 方法和 URI.我想更改此设置以匹配请求正文:

So request matching rule matches only on HTTP method and URI. I want to change this setting to also match request body:

VCR.configure do |c|
  c.cassette_library_dir = 'spec/vcr_cassettes'
  c.hook_into :webmock
  c.configure_rspec_metadata!
  c.default_cassette_options = {
    :match_requests_on => [:uri, :method, :body],
  }
end

但是由于我的项目中已经有很多测试,我想逐步进行,仅对某些测试启用此新限制,以便其他测试(使用旧磁带)不会中断.

but since I already have a lot of tests in my project, I would like to do it gradually, activating this new restriction only to some of the tests, so the other ones (with old cassettes) would't break.

有什么方法可以将参数传递给 RSpec 测试,以便为某些特定测试或测试组设置自定义请求匹配规则?

Is there any way to pass a parameter to RSpec tests to have a custom request matching rule only for some specific tests or groups of tests?

我想像这样

it 'reverts transaction', :vcr, :body_matching => true do
    # something
end

然后根据body_matching参数动态更改设置.

and then change settings dynamically according to body_matching parameter.

推荐答案

:vcr 元数据可以设置为用于插入盒式磁带的选项哈希.因此你可以这样做

The :vcr metadata can be set to a Hash of options which will be used for the inserted cassette. Therefore you could do

it 'reverts transaction', vcr: { :match_requests_on => [:uri, :method, :body] } do
  # something
end

为了使它更好,您可以将该哈希分配给一个变量,然后将其设置为 :vcr 选项.如果你想更进一步,你需要在 set 之前/之后创建你自己的 RSpec,然后设置你自己的元数据名称,然后在元数据中不包含 :vcr(因为你需要做你的自己的 (insert_cassette) 调用).请参阅 https://github.com/vcr/vcr/blob/31e2cba76c0c9a60c3de5d5ece1c87563bfeacf7/lib/vcr/test_frameworks/rspec.rb#L32 用于 VCR 安装之前/之后的挂钩.

To make it nicer you could assign that hash to a variable and then just set that to the :vcr option. If you wan to go further than you'd need to create your own RSpec before/after set keyed off your own metadata name and then not include :vcr in the metadata (since you will need to do your own (insert_cassette) call). See https://github.com/vcr/vcr/blob/31e2cba76c0c9a60c3de5d5ece1c87563bfeacf7/lib/vcr/test_frameworks/rspec.rb#L32 for the before/after hooks VCR installs.

这篇关于某些特定 RSpec 测试的自定义 VCR 请求匹配选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆