Skip to content

Instantly share code, notes, and snippets.

@jrom
Created October 26, 2011 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrom/1315954 to your computer and use it in GitHub Desktop.
Save jrom/1315954 to your computer and use it in GitHub Desktop.
Middleware YAML Recorder

This is a WIP, the idea is to copy VCR's behavior but with intercepted Rack requests.

TODO

  • Specify which URL's must be intercepted/recorded
  • Ensure complex bodies are safely stored in the YAML
  • Keep some kind of application-wide list of accessed requests so tests can see what has been issued and with what parameters.
  • Add query_string to the file name so we can have two different mocks for the same URL with different query strings.
  • Whatever we find useful for it!
class RecordMiddleware
def initialize(app, options = {})
@options = options
@options[:path] ||= 'fixtures/records'
@app = app
end
def call(env)
request = Rack::Request.new(env)
if request_recorded?(request)
recorded_response(request)
else
@app.call(env).tap do |response|
record_response(request, response)
end
end
end
private
def request_key(request)
request.path.gsub('/', '-')[1..-1].presence || 'root'
end
def path_to_record(request)
File.join(@options[:path], request_key(request)) + '.yml'
end
def request_recorded?(request)
File.exists?(path_to_record(request))
end
def recorded_response(request)
data = YAML.load_file(path_to_record(request))
[data[:status], data[:headers], data[:body]]
end
def record_response(request, response)
FileUtils.mkdir_p(@options[:path]) unless File.exists?(@options[:path])
File.open(path_to_record(request), 'w') do |f|
YAML.dump(hashified_response(request, response), f)
end
end
def hashified_response(request, response)
{
:path => request.path,
:status => response[0],
:headers => response[1],
:body => response[2].body
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment