diff --git a/lib/httparty.rb b/lib/httparty.rb index bffac7c3..04344b74 100644 --- a/lib/httparty.rb +++ b/lib/httparty.rb @@ -494,10 +494,17 @@ def default_options #:nodoc: def perform_request(http_method, path, options, &block) #:nodoc: options = default_options.merge(options) + process_headers(options) process_cookies(options) Request.new(http_method, path, options).perform(&block) end + def process_headers(options) + if options[:headers] && headers.any? + options[:headers] = headers.merge(options[:headers]) + end + end + def process_cookies(options) #:nodoc: return unless options[:cookies] || default_cookies.any? options[:headers] ||= headers.dup diff --git a/spec/httparty/httparty_spec.rb b/spec/httparty/httparty_spec.rb new file mode 100644 index 00000000..d30d147b --- /dev/null +++ b/spec/httparty/httparty_spec.rb @@ -0,0 +1,51 @@ +require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper')) + +describe HTTParty do + + class SimpleClient + include HTTParty + end + + class HeadersClient + include HTTParty + headers "Accept" => "application/json" + end + + def request + FakeWeb.last_request + end + + context 'request headers' do + + before do + @headers = { "User-Agent" => 'my-ruby', 'Content-Type' => 'text/plain' } + @uri = "http://localhost/request_headers" + FakeWeb.register_uri(:get, @uri, :body => "OK") + end + + it 'should correctly set the request headers' do + SimpleClient.get(@uri, :headers => @headers) + @headers.each do |name, value| + request[name].should == value + end + end + + it 'should correctly mix the current request and default headers' do + HeadersClient.get(@uri, :headers => @headers) + @headers.each do |name, value| + request[name].should == value + end + request['Accept'].should == 'application/json' + end + + it 'should correctly override default headers with request headers' do + HeadersClient.get(@uri, :headers => @headers.merge('Accept' => 'text/html')) + @headers.each do |name, value| + request[name].should == value + end + request['Accept'].should == 'text/html' + end + + end + +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index a7aeb9a5..9db324d0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,5 @@ $:.push File.expand_path("../lib", __FILE__) + require "httparty" require 'spec/autorun'