A gem that allows you to define a Mock for API response when testing the ability to access external APIs.
group :test do
  gem 'webmock'
end
$ bundle install --path vendor/bundle
model/smaple.rb
require 'net/https'
require 'uri'
class Sample
  include ActiveModel::Model
  def get_request(api_url, params)
    uri = URI(api_url)
    uri.query = params
    request(uri)
  end
end
When the above get_request method is executed, the contents of the stub defined in WebMock are returned.
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe Abyss, type: :model do
  describe 'facet', type: :facet 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 'debug' do
      res = subject.send(:get_request, 'http://www.example.com', '')
      puts res.body # This is a mock
    end
  end
end
-Stub API access using WebMock in Rails development
Recommended Posts