diff --git a/lib/google/apis/core/api_command.rb b/lib/google/apis/core/api_command.rb index 519c0c97e..5715d2f00 100644 --- a/lib/google/apis/core/api_command.rb +++ b/lib/google/apis/core/api_command.rb @@ -105,6 +105,10 @@ module Google end end + def allow_form_encoding? + request_representation.nil? && super + end + private # Attempt to parse a JSON error message, returning the first found error diff --git a/lib/google/apis/core/http_command.rb b/lib/google/apis/core/http_command.rb index bcea5c53a..75bf83d39 100644 --- a/lib/google/apis/core/http_command.rb +++ b/lib/google/apis/core/http_command.rb @@ -146,7 +146,7 @@ module Google self.url = url.expand(params) if url.is_a?(Addressable::Template) url.query_values = query.merge(url.query_values || {}) - if [:post, :put].include?(method) && body.nil? + if allow_form_encoding? @form_encoded = true self.body = Addressable::URI.form_encode(url.query_values(Array)) self.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' @@ -306,6 +306,10 @@ module Google req.options.open_timeout = options.open_timeout_sec end + def allow_form_encoding? + [:post, :put].include?(method) && body.nil? + end + private def form_encoded? diff --git a/spec/google/apis/core/api_command_spec.rb b/spec/google/apis/core/api_command_spec.rb index 4920c496c..40ed3b90e 100644 --- a/spec/google/apis/core/api_command_spec.rb +++ b/spec/google/apis/core/api_command_spec.rb @@ -17,7 +17,7 @@ require 'google/apis/core/api_command' require 'google/apis/core/json_representation' require 'hurley/test' -RSpec.describe Google::Apis::Core::HttpCommand do +RSpec.describe Google::Apis::Core::ApiCommand do include TestHelpers include_context 'HTTP client' @@ -40,20 +40,28 @@ RSpec.describe Google::Apis::Core::HttpCommand do command = Google::Apis::Core::ApiCommand.new(:post, 'https://www.googleapis.com/zoo/animals') command.request_representation = representer_class command.request_object = request + command.query['a'] = 'b' command end before(:example) do - stub_request(:post, 'https://www.googleapis.com/zoo/animals') + stub_request(:post, 'https://www.googleapis.com/zoo/animals?a=b') .to_return(headers: { 'Content-Type' => 'application/json' }, body: %({})) end it 'should serialize the request object' do command.execute(client) - expect(a_request(:post, 'https://www.googleapis.com/zoo/animals').with do |req| + expect(a_request(:post, 'https://www.googleapis.com/zoo/animals?a=b').with do |req| be_json_eql(%({"value":"hello"})).matches?(req.body) end).to have_been_made end + + it 'should not form encode query parameters when body expected but nil' do + command.query['a'] = 'b' + command.request_object = nil + command.execute(client) + expect(a_request(:post, 'https://www.googleapis.com/zoo/animals?a=b').with(body: nil)).to have_been_made + end end context('with a JSON response') do