Class: Mock5::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/mock5/api.rb

Overview

A class representing an API mock

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint = nil) { ... } ⇒ Mock5::Api

Returns an instance of Mock5::Api

Examples:

my_mock_api = Mock5::Api.new("http://example.com") do
  get "posts" do
    [
      {id: 1, body: "a posy body"},
      {id: 2, body: "another post body"}
    ].to_json
  end

  post "posts" do
    halt 201, "The post was created successfully"
  end
end

Parameters:

  • endpoint (String, Regexp) (defaults to: nil)

    a url of the API service to endpoint to mock. Can only contain schema and hostname, path should be empty.

Yields:

  • a block passed to Sinatra to initialize an app



38
39
40
41
# File 'lib/mock5/api.rb', line 38

def initialize(endpoint=nil, &block)
  @app = Sinatra.new(&block)
  @endpoint = normalize_endpoint(endpoint)
end

Instance Attribute Details

#appSinatra::Base (readonly)

Returns a Sinatra app mocking the API.

Returns:

  • (Sinatra::Base)

    a Sinatra app mocking the API



10
11
12
# File 'lib/mock5/api.rb', line 10

def app
  @app
end

#endpointRegexp (readonly)

Returns a regexp to match the API request urls.

Returns:

  • (Regexp)

    a regexp to match the API request urls



13
14
15
# File 'lib/mock5/api.rb', line 13

def endpoint
  @endpoint
end

Instance Method Details

#request_stubWebMock::RequestStub

Returns webmock request stub built with Sinatra app and enpoint url

Returns:

  • (WebMock::RequestStub)


46
47
48
# File 'lib/mock5/api.rb', line 46

def request_stub
  @request_stub ||= WebMock::RequestStub.new(:any, endpoint).tap{ |s| s.to_rack(app) }
end