Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an HTTP response in Ruby

I'm working on an application that reaches out to a web service. I'd like to develop a proxy class that returns a fake response from the service, so I don't have to constantly be hitting it with requests while I'm developing/testing other parts of the app.

My application is expecting a response generated via Net::HTTP.

response = Net::HTTP.get(URI.parse('http://foo.com'))

case response
when Net::HTTPOK
  # do something fun

when Net::HTTPUnauthorized
  # you get the idea

How can I manufacture a response object, give it all the right headers, return a body string, etc?

response = ProxyClass.response_object

case response
when Net::HTTPOk
  # my app doesn't know it's being lied to

Thanks.

like image 697
Bryan M. Avatar asked Apr 21 '09 01:04

Bryan M.


4 Answers

It's actually not that hard to roll your own fake responses directly with Net::HTTP. Here's a simple 200 OK with a cookie header:

def fake_response
  net_http_resp = Net::HTTPResponse.new(1.0, 200, "OK")
  net_http_resp.add_field 'Set-Cookie', 'Monster'
  RestClient::Response.create("Body goes here", net_http_resp, nil)
end

Since few of us are using raw Net::HTTP anymore, the (optional) last line wraps it up as a RestClient::Response, which can then be stubbed into RestClient:

stub(RestClient).post(anything) { fake_response }
like image 53
lambshaanxy Avatar answered Nov 19 '22 18:11

lambshaanxy


I would start with FakeWeb and see if that meets your needs. If it doesn't you can probably gut whatever you need out of the internals and create your own solution.

like image 35
gtd Avatar answered Nov 19 '22 18:11

gtd


I know this post is old, but instead of FakeWeb which seems to be largely dead, try webmock. It seems to be more full-featured and very active.

like image 5
David van Geest Avatar answered Nov 19 '22 18:11

David van Geest


I would look into a mocking library like mocha.

Then you should be able to setup a mock object to help test:

Then following example is from Tim Stephenson's RaddOnline blog, which also includes a more complete tutorial:

def setup
 @http_mock = mock('Net::HTTPResponse')
 @http_mock .stubs(:code => '200', :message => "OK", :content_type => > "text/html", :body => '<title>Test</title><body>Body of the page</body>')
end
like image 4
csexton Avatar answered Nov 19 '22 18:11

csexton