diff --git a/lib/webmock/http_lib_adapters/httpclient_adapter.rb b/lib/webmock/http_lib_adapters/httpclient_adapter.rb index 2ac4054e3..b51a213cc 100644 --- a/lib/webmock/http_lib_adapters/httpclient_adapter.rb +++ b/lib/webmock/http_lib_adapters/httpclient_adapter.rb @@ -72,13 +72,19 @@ def do_get(req, proxy, conn, stream = false, &block) res = if stream do_get_stream_without_webmock(req, proxy, conn, &block) + elsif block + body = '' + do_get_block_without_webmock(req, proxy, conn) do |http_res, chunk| + body += chunk + block.call(http_res, chunk) + end else - do_get_block_without_webmock(req, proxy, conn, &block) + do_get_block_without_webmock(req, proxy, conn) end res = conn.pop conn.push(res) if WebMock::CallbackRegistry.any_callbacks? - webmock_response = build_webmock_response(res) + webmock_response = build_webmock_response(res, body) WebMock::CallbackRegistry.invoke_callbacks( {:lib => :httpclient, :real_request => true}, request_signature, webmock_response) @@ -133,7 +139,7 @@ class WebMockJSONClient < JSONClient end end - def build_webmock_response(httpclient_response) + def build_webmock_response(httpclient_response, body = nil) webmock_response = WebMock::Response.new webmock_response.status = [httpclient_response.status, httpclient_response.reason] @@ -147,7 +153,9 @@ def build_webmock_response(httpclient_response) end end - if httpclient_response.content.respond_to?(:read) + if body + webmock_response.body = body + elsif httpclient_response.content.respond_to?(:read) webmock_response.body = httpclient_response.content.read body = HTTP::Message::Body.new body.init_response(StringIO.new(webmock_response.body)) diff --git a/spec/acceptance/httpclient/httpclient_spec.rb b/spec/acceptance/httpclient/httpclient_spec.rb index 05c392310..cf1402e5a 100644 --- a/spec/acceptance/httpclient/httpclient_spec.rb +++ b/spec/acceptance/httpclient/httpclient_spec.rb @@ -139,7 +139,6 @@ def filter_response(request, response) end context 'session headers' do - it "client sends a User-Agent header when given an agent_name explicitly to the client" do user_agent = "Client/0.1" stub_request(:get, "www.example.com").with(:headers => { 'User-agent' => "#{user_agent} #{HTTPClient::LIB_NAME}" }) @@ -161,7 +160,6 @@ def filter_response(request, response) stub_request(:get, "www.example.com").with(:headers => headers) HTTPClient.new.get("www.example.com", nil, headers) end - end context 'httpclient response header' do @@ -171,4 +169,21 @@ def filter_response(request, response) expect(message.header.request_uri.to_s).to eq('www.example.com') end end + + context 'httpclient streams response' do + before do + WebMock.allow_net_connect! + WebMock.after_request(:except => [:other_lib]) do |_, response| + @response = response + end + end + + it 'sets the full body on the webmock response' do + body = '' + result = HTTPClient.new.request(:get, 'http://www.example.com/') do |http_res, chunk| + body += chunk + end + expect(@response.body).to eq body + end + end end