Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created February 21, 2015 12:37
Show Gist options
  • Select an option

  • Save tobiashm/0f9d3c1045b0ab1f65d9 to your computer and use it in GitHub Desktop.

Select an option

Save tobiashm/0f9d3c1045b0ab1f65d9 to your computer and use it in GitHub Desktop.
Create a simple mock server from API Blueprint document for testing
require "addressable/template"
require "redsnow"
require "sinatra"
class BlueprintMockServer
def initialize(base_url, blueprint)
@mocks = {}
api = RedSnow.parse(File.read(blueprint.to_s))
api.ast.resource_groups.flat_map(&:resources).each do |resource|
uri_template = Addressable::Template.new(base_url + resource.uri_template)
@mocks[uri_template] = Hash[resource.actions.map { |a| [a.method, a] }]
end
end
def call(env)
request = Rack::Request.new(env)
action = match request
return [404, {}, []] unless action
responses(action).first || [500, {}, []]
end
def match(request)
template = @mocks.keys.find { |uri| uri.match(request.url) }
@mocks[template][request.request_method] if template
end
def responses(action)
action.examples.flat_map(&:responses).map do |response|
[response.name.to_i, headers(response), [response.body]]
end
end
def headers(response)
Hash[response.headers.collection.map { |item| [item[:name], item[:value]] }]
end
end
require "webmock"
require "blueprint_mock_server"
base_url = "http://my-api-host"
blueprint = Rails.root.join("doc", "my-api-doc.apib")
app = BlueprintMockServer.new(base_url, path_to_blueprint)
WebMock::StubRegistry.instance.register_request_stub(
WebMock::RequestStub.new(:any, /#{base_url}/)
).to_rack(app)
@tobiashm
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment