18
15

More than 5 years have passed since last update.

VCR/WebMock/RSpecで外部と通信を行うテストを書く

Posted at

VCRのインストール

Gemfileに以下を追加してbundle install

group :test do
  gem 'vcr'
  gem 'webmock', ">= 1.8.0", "< 1.12"
end

RSpec用設定

spec/spec_helper.rbに以下の内容を追加

spec/spec_helper.rb
RSpec.configure do |config|
  #  some other codes… #

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

  # SpecのDescriptionを元にVCRのファイル名を生成する
  config.around(:each, :vcr) do |example|
    name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
    options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
    options.reverse_merge!(record: :new_episodes)
    VCR.use_cassette(name, options) { example.call }
  end
end

c.cassette_library_dirの場所は色々流儀があるようだが、通常FactoryGirlのfactoryデータがspec/factories下に入っているはずなので、それに合わせる形で、spec/vcr_cassettesと指定している。

参考:

18
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15