14
8

More than 3 years have passed since last update.

Rspecでwebmockを使う

Last updated at Posted at 2020-06-02

概要

外部APIなどにアクセスする機能をテストする際に、APIレスポンスのMockを定義できるgem。

Gemfileにwebmockを追加

group :test do
  gem 'webmock'
end
$ bundle install --path vendor/bundle

テスト対象のmodel

model/sample.rb
require 'net/https'
require 'uri'

class Sample
  include ActiveModel::Model

  def request_api(api_url, params)
    uri = URI(api_url)
    uri.query = params
    request(uri)
  end
end

rspecを作る

前述のrequest_apiメソッドを実行すると、WebMockで定義したstubの内容が返る。

require 'rails_helper'
require 'webmock/rspec'

RSpec.describe Sample, type: :model do
  describe 'request_api', type: :request_api do
    before do
      WebMock.enable!
      WebMock.stub_request(:any, "www.example.com").to_return(
        body: "This is a mock",
        status: 200,
        headers: { 'Content-Length' => 7 }
      )
    end
    subject { Sample.new }
    it 'returns body' do
      res = subject.send(:request_api, 'http://www.example.com', '')
      expect(res.body).to eq('This is a mock')
    end
  end
end

参考

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