Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created March 18, 2013 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfborjas/5187243 to your computer and use it in GitHub Desktop.
Save lfborjas/5187243 to your computer and use it in GitHub Desktop.
Serves a rack app based on paths/responses defined in a cucumber feature
require 'gherkin/parser/parser'
require 'gherkin/formatter/json_formatter'
#This is intended to be mounted on top of a rails app with
#mount FakeEndpoints => "/fake_api"
#this allows clients to play around with an intended implementation of the API without it being actually coded at all
#the features look like
# Given I GET /an/endpoint; Then the JSON response is:
class FakeEndpoints
def initialize
@routes = gather_routes
end
def call(env)
payload = @routes[env["PATH_INFO"]]
if payload
[200, {"Content-Type" => "application/hal+json"}, [payload]]
else
[404, {"Content-Type" => "application/json"}, ['{"message": "these are not the bytes you are looking for"}']
end
end
private
def gather_routes
Walker.texas_ranger
end
class Walker
def self.texas_ranger
chuck = Walker.new
chuck.visit("#{Rails.root}/features/api_endpoints.feature")
chuck.gathered
end
attr_reader :gathered
def initialize
@gathered = {}
end
def visit(path)
io = StringIO.new
formatter = Gherkin::Formatter::JSONFormatter.new(io)
parser = Gherkin::Parser::Parser.new(formatter)
parser.parse(IO.read(path), path, 0)
formatter.done
parsed = JSON.parse(io.string)
feature = parsed.first
feature["elements"].each do |scenario|
next if scenario["steps"].nil?
next unless scenario["steps"].size == 2
route = scenario["steps"].first["name"].match(/I GET "(.*)"/)[1]
payload = scenario["steps"].last["doc_string"]["value"].gsub(/\s+/, " ")
gathered.merge!({route => payload})
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment