Created
October 13, 2009 17:08
-
-
Save kalv/209380 to your computer and use it in GitHub Desktop.
RecordHttp - helps save http requests into files when testing
This file contains 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
# Record HTTP is to help recording the http calls for further testing | |
# | |
# usage: | |
# require 'record_http' | |
# set up the directory it needs to save the responses | |
# RecordHttp.save_path = '../spec/data' | |
# RecordHttp.include_headers = true | |
# RecordHttp.file_prefix = 'http_' | |
# | |
# Run your net http requests, tests, gems that use net/http and watch everything save away! | |
# Net::HTTP.get(URI.parse("http://localhost")) | |
require 'net/http' | |
module RecordHttp | |
@@save_path = nil | |
@@include_headers = false | |
@@file_prefix = "http_" | |
def self.save_path | |
@@save_path | |
end | |
def self.save_path=(save_path) | |
@@save_path = save_path | |
end | |
def self.include_headers=(include_headers) | |
@@include_headers = include_headers | |
end | |
def self.file_prefix=(file_prefix) | |
@@file_prefix = file_prefix | |
end | |
def self.save_res(address,req,res) | |
pathname = req.path.gsub("/","_") | |
filename = @@save_path+"/"+@@file_prefix + address + (pathname ? "" : pathname) | |
File.open(filename,"w") do |file| | |
if @@include_headers | |
file.write("HTTP/#{res.http_version} #{res.code} #{res.message}\n") | |
res.to_hash.each do |key,value| | |
file.write("#{key.capitalize}: #{value}\n") | |
end | |
file.write("\n") | |
end | |
file.write(res.body) | |
end | |
puts "Saved file #{filename} with response from http://#{address}#{req.path}" | |
end | |
end | |
# set save path | |
RecordHttp.save_path = '../spec/data' | |
RecordHttp.include_headers = false | |
RecordHttp.file_prefix = 'http_' | |
# override Net::Http at request level to get post / get / put / etc | |
module Net | |
class HTTP | |
alias :old_request :request | |
def request(req, body = nil, &block) | |
res = old_request(req, body, &block) | |
begin | |
RecordHttp.save_res(@address,req,res) | |
rescue | |
puts "Error saving response #{$!}" | |
end | |
res | |
end | |
end | |
end | |
# Just run Net::Http | |
#puts Net::HTTP.get(URI.parse("http://localhost")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment