Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec Trouble mocking HTTP request

How do I write RSpec for ...

Net::HTTP::Proxy(PROXY_HOST, PROXY_PORT).start(url.host) do |http|
  request = Net::HTTP::Post.new(url.path)
  request.form_data = {'param1' => 'blah1', 'param2' => 'blah2'}
  response = http.request(request)
end

This is as far as I got ...

@mock_http = mock('http')
@mock_http.should_receive(:start).with(@url.host)
Net::HTTP.should_receive(:Proxy).with(PROXY_HOST, PROXY_PORT).and_return(@mock_http)
Net::HTTP::Post.should_receive(:new).with(@url.path).and_return(@mock_http)

However when trying ...

Net::HTTP::Post.should_receive(:new).with(@url.path).and_return(@mock_http)

... received the following response ...

<Net::HTTP::Post (class)> expected :new with ("/some/path") once, but received it 0 times

A complete solution would be greatly appreciated!

like image 390
user1186842 Avatar asked Feb 03 '12 06:02

user1186842


1 Answers

I'm not sure what you're trying to test exactly, but here's how to stub this http request using webmock:

In Gemfile:

group :test do
  gem 'webmock'
end

In spec/spec_helper.rb:

require 'webmock/rspec'
WebMock.disable_net_connect!(:allow_localhost => true)

In your test:

stub_request(:post, url.host).
  with(:body => {'param1' => 'blah1', 'param2' => 'blah2'},
  to_return(:status => 200, :body => '{ insert your response body expectation here }'
like image 138
Elad Avatar answered Sep 25 '22 05:09

Elad