user1186842
user1186842

Reputation: 73

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!

Upvotes: 5

Views: 3875

Answers (1)

Elad
Elad

Reputation: 3130

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 }'

Upvotes: 5

Related Questions