class ServiceContractWebmock::ServiceMock

Attributes

base_url[R]
contract[R]
name[R]
resources[R]

Public Class Methods

new(name, resources, contract, base_url) click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 7
def initialize(name, resources, contract, base_url)
  @name = name
  @resources = resources
  @contract = contract
  @base_url = base_url
end

Public Instance Methods

stub_index_request() click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 25
def stub_index_request
  stub_request(:get, "#{name}\\.json\\??$")
    .to_return(body: { name => resources }.to_json,
              headers: { 'Content-Type' => 'application/json' })
end
stub_request(method, path) click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 21
def stub_request(method, path)
  WebMock.stub_request(method, %r{#{base_url}/#{path}})
end
stub_search_request() click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 54
def stub_search_request
  matcher = ContractMatcher.new(contract.endpoint("index"), resources)
  stub_request(:get, "#{name}\\.json\\?#{matcher.to_regex}").
    to_return do |request|
      {
        body: { name => matcher.found(request.uri.query) }.to_json,
        headers: { 'Content-Type' => 'application/json' }
      }
    end
end
stub_show_request() click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 31
def stub_show_request
  return if contract.endpoint("show").nil?
  key = contract.endpoint("show").parameters.first.name
  stub_request(:get, "#{name}/\\d+\\.json").
    to_return do |request|
      id = request.uri.path.scan(/\/(\d+)\.json/)[0][0].to_i
      found = resources.select {|r| r[key] == id}

      if found.present?
        {
          body: { name => found }.to_json,
          headers: { 'Content-Type' => 'application/json' }
        }
      else
        {
          body: { meta: { status: 404, errors: ['resource not found'] } }.to_json,
          headers: { 'Content-Type' => 'application/json' },
          status: 404
        }
      end
    end
end
webmock!() { |self| ... } click to toggle source
# File lib/service_contract_webmock/service_mock.rb, line 14
def webmock!
  stub_index_request
  stub_search_request
  stub_show_request
  yield self if block_given?
end