Created
February 21, 2015 12:37
-
-
Save tobiashm/0f9d3c1045b0ab1f65d9 to your computer and use it in GitHub Desktop.
Create a simple mock server from API Blueprint document for testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a gem: https://github.com/karnov/apib-mock_server