use*_*842 4 rspec ruby-on-rails
我如何为...编写RSpec
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
Run Code Online (Sandbox Code Playgroud)
据我所知...
@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)
Run Code Online (Sandbox Code Playgroud)
但是当尝试...
Net::HTTP::Post.should_receive(:new).with(@url.path).and_return(@mock_http)
Run Code Online (Sandbox Code Playgroud)
...收到以下回应...
<Net::HTTP::Post (class)> expected :new with ("/some/path") once, but received it 0 times
Run Code Online (Sandbox Code Playgroud)
完整的解决方案将不胜感激!
我不确定您要测试的是什么,但是这是使用webmock存根http请求的方法:
在Gemfile
:
group :test do
gem 'webmock'
end
Run Code Online (Sandbox Code Playgroud)
在spec/spec_helper.rb
:
require 'webmock/rspec'
WebMock.disable_net_connect!(:allow_localhost => true)
Run Code Online (Sandbox Code Playgroud)
在您的测试中:
stub_request(:post, url.host).
with(:body => {'param1' => 'blah1', 'param2' => 'blah2'},
to_return(:status => 200, :body => '{ insert your response body expectation here }'
Run Code Online (Sandbox Code Playgroud)