Repository URL to install this package:
|
Version:
7.3.3 ▾
|
# frozen_string_literal: true
require 'webmock/rspec'
require 'delegate'
# Mixin to provide access to webmock stubs with some wrapping
module WebMockHelper
# Wrapper for WebMock stubs and expose extra methods
class StubDelegator < SimpleDelegator
include WebMock::API
def _wrap(stub)
StubDelegator.new(stub)
end
def with(...)
_wrap __getobj__.with(...)
end
def json!
_wrap with(headers: { content_type: 'application/json' })
end
def with_auth(user: 'user', password: 'password')
_wrap with(basic_auth: [user, password])
end
end
def stub_request(...)
StubDelegator.new WebMock::API.stub_request(...)
end
def self.included(base)
base.extend Macros
end
# Macros for defining stubbed HTTP methods in API classes
module Macros
def define_stub(method, *args)
define_method :"stub_#{method}!" do
instance_variable_set :"@#{method}", stub_request(method, *args)
self
end
attr_reader method
end
end
end
# URL stubbing class operating on a fixed URL
# On instantiation specify whether it expects json and/or basic auth
# Call e.g. #stub_get! and then reference the stub with #get
# For APIs with sub-URLs, derive from this class
class SimpleApiHelper
include WebMockHelper
def initialize(url, json: true, auth: true)
@url = url
@json = json
@auth = auth
end
def stub_request(method)
s = super(method, @url)
s = s.json! if @json
s = s.with_auth if @auth
s
end
%i[get post put patch delete].each { |m| define_stub(m) }
end