学习RUBY:在GEMS共享VCR磁带

128 阅读2分钟

学习RUBY:在GEMS共享VCR磁带

去年我发布了一个关于[Mocking Web APIs]的提示,这篇文章略有类似:使用来自你所依赖的gem的磁带,同时使用你自己的磁带

想一想下面的情况。

你依赖于一个Web API(在一个名为fancy-web-api 的 gem 中实现),这个 gem 在内部使用VCR进行测试,而你使用来自该API的响应来建立只适用于你的实现的具体对象。

你怎样才能重用那些在fancy-web-api 中定义的磁带?

让我们想一想完美的世界场景:我们同时控制着fancy-web-api 和一个使用这个 gem 的新应用程序。这当然是解释这个解决方案的最简单的方式,但是如果这不是你的情况,那么你可以为你所依赖的 gem 提供以下解决方案。

从fancy-web-api暴露盒式磁带

重用盒式磁带,或实际上任何其他用于测试的东西(如工厂或固定装置)的关键是公开它们,以便可以从外部加载。在盒式磁带的情况下,你会在你的fancy-web-api 中包含一个类似这样的文件。

# frozen_string_literal: true

# Takeaways
# * This file lives in *your gem* in "web_api/vcr_testing.rb"
# * VCR cassettes are defined in "../../../spec/cassettes" relative to this file
module FancyWebAPI
  class VCRTesting
    CASSETTES_PATH = File.expand_path('../../..', __FILE__).freeze

    class << self
      def configure!(config)
        config.configure_rspec_metadata!
        config.cassette_library_dir = File.join(ROOT_PATH, 'spec', 'cassettes')
        config.hook_into :webmock
      end
    end # << self
  end # class
end

因此,在你的fancy-web-api 和你的新应用程序中,你都需要在你的spec_helper.rb (或类似的)中使用你的录像机磁带。

# frozen_string_literal: true
require 'fancy_web_api/vcr_testing'

VCR.configure do |config|
  FancyWebAPI::VCRTesting.configure!(config)
end

规格使用

在调用FancyWebAPI::VCRTesting.configure! 之后,你应该能够像使用正常的录像机语法那样使用磁带,所以假设fancy-web-api 定义了一个名为的磁带。https_create,这就可以了。

require 'spec_helper'

describe ClassUsingHTTPSCreate, type: :model do
  context 'when request is valid', vcr: { cassette_name: 'https_create' } do
    # Stuff happens here...
  end
end

在使用其他盒式磁带时使用你自己的盒式磁带

现在,当你打算同时使用你自己的磁带和fancy-web-api 中定义的磁带时,棘手的部分来了。答案很简单,杂耍 cassette_library_dir= 。最优雅的方法是什么?

我个人会用RSpec.configure 来定义我想做的事情,例如。

def use_my_vcr
  VCR.configure do |config|
    # Configure my VCR accordingly
  end
end

def use_fancy_web_api_vcr
  VCR.configure do |config|
    FancyWebAPI::VCRTesting.configure!(config)
  end
end

RSpec.configure do |config|
  config.before(:all, :use_my_vcr) { use_my_vcr }
  config.before(:all, :use_fancy_web_api_vcr) { use_fancy_web_api_vcr }
end