如何告诉 VCR 我希望它完全忽略规范文件?
我读过一篇Google Groups 上的帖子,建议要么允许真实的 HTTP 请求,要么显式关闭 VCR。
在我看来,更有用的是 VCR 不要介入,除非规范具有
:vcr
元数据标签。我不想在 before
/after
中关闭并重新打开 VCR,因为我不知道它是否事先已打开。我不想允许跨所有规范的真正 HTTP 请求,只允许一些特定的请求。
有什么办法可以让VCR更有选择性吗?
这不是最优雅的解决方案,但您可以使用实例变量将配置返回到其原始设置
describe "A group of specs where you want to allow http requests" do
before do
VCR.configure do |c|
@previous_allow_http_connections = c.allow_http_connections_when_no_cassette?
c.allow_http_connections_when_no_cassette = true
end
end
after do
VCR.configure do |c|
c.allow_http_connections_when_no_cassette = @previous_allow_http_connections
end
end
# Specs in this block will now allow http requests to be made
end
我发现这对于我最初启动并运行 API 并希望能够调试我发出的请求很有帮助。一旦 API 正常工作,我就可以删除之前和之后的块,并正常使用 VCR。
就我而言,我不想允许非 VCR 规格的真正 HTTP 连接,我只是希望对这些规格禁用 VCR,以便 Webmock 直接处理它们。这对我有用:
RSpec.configure do |config|
config.around do |example|
if example.metadata.key?(:vcr)
example.run
else
VCR.turned_off { example.run }
end
end
end
有几种方法可以让您做到这一点,这里有一些资源:
按照这些思路可能会起作用:
# In the beginning of your describe block
around do |example|
VCR.turned_off { example.run }
end
或
let(:request) {
VCR.turned_off do
get some_path(params)
end
end
it { expect { request } .to .... }
在使用关闭方法之前,您可能需要使用
VCR.eject_cassette
,具体取决于您在规范中所做的操作。
根据凯西的回答,我想出了这个辅助模块:
module VcrHelpers
def self.perform_without_cassette
VCR.configure { |c| c.allow_http_connections_when_no_cassette = true }
yield
ensure
VCR.configure { |c| c.allow_http_connections_when_no_cassette = false }
end
end
然后可以从任何规范调用它,如下所示:
VcrHelpers.perform_without_cassette do
some_http_request
end
请参阅 docs 了解测试中包含/要求的内容。
这样你就可以重用这个逻辑
shared_context :vcr_allows_http_connections do
before do
VCR.configure do |c|
@previous_allow_http_connections = c.allow_http_connections_when_no_cassette?
c.allow_http_connections_when_no_cassette = true
end
end
after do
VCR.configure do |c|
c.allow_http_connections_when_no_cassette = @previous_allow_http_connections
end
end
end
然后你就可以像这样使用它:
RSpec.describe :allow_all, type: :request do
include_context :vcr_allows_http_connections
# specs with http connections for the rest of the describe block
end
# OR
RSpec.describe :allow_some, type: :request do
# specs with without http connections or vcr cassettes
include_context :vcr_allows_http_connections do
# specs with http connections only for this block
end
end