Browse files

Add before_http_request hook.

For issue #91.
  • Loading branch information...
1 parent 426b0a1 commit a8110df3f5de02d30e6ae96ffa6d8c7bd01f17ba @myronmarston myronmarston committed Nov 16, 2011
View
1 lib/vcr/configuration.rb
@@ -9,6 +9,7 @@ class Configuration
define_hook :before_record
define_hook :before_playback
define_hook :after_library_hooks_loaded
+ define_hook :before_http_request
def initialize
@allow_http_connections_when_no_cassette = nil
View
6 lib/vcr/request_handler.rb
@@ -1,6 +1,7 @@
module VCR
class RequestHandler
def handle
+ invoke_before_request_hook
return on_ignored_request if should_ignore?
return on_stubbed_request if stubbed_response
return on_recordable_request if VCR.real_http_connections_allowed?
@@ -9,6 +10,11 @@ def handle
private
+ def invoke_before_request_hook
+ return if disabled?
+ VCR.configuration.invoke_hook(:before_http_request, tag = nil, vcr_request)
+ end
+
def should_ignore?
disabled? || VCR.request_ignorer.ignore?(vcr_request)
end
View
40 spec/support/shared_example_groups/hook_into_http_library.rb
@@ -117,6 +117,46 @@ def self.test_playback(description, url)
test_playback "with an encoded ampersand", "http://example.com:80/search?q=#{CGI.escape("Q&A")}"
end
+ context 'when there is a before_http_request hook' do
+ let(:string_in_cassette) { 'example.com get response 1 with path=foo' }
+
+ it 'plays back the cassette when a request is made' do
+ VCR.configure do |c|
+ c.cassette_library_dir = File.join(VCR::SPEC_ROOT, 'fixtures')
+ c.before_http_request do |request|
+ VCR.insert_cassette('fake_example_responses', :record => :none)
+ end
+ end
+ get_body_string(make_http_request(:get, 'http://example.com/foo')).should eq(string_in_cassette)
+ end
+
+ it 'yields the request to the hook' do
+ request = nil
+ VCR.configure do |c|
+ c.ignore_request { |r| true }
+ c.before_http_request { |r| request = r }
+ end
+ url = "http://localhost:#{VCR::SinatraApp.port}/foo"
+ make_http_request(:get, url)
+ request.method.should be(:get)
+ request.uri.should eq(url)
+ end
+
+ it 'does not get invoked if the library hook is disabled' do
+ VCR.library_hooks.should respond_to(:disabled?)
+ VCR.library_hooks.stub(:disabled? => true)
+
+ hook_called = false
+ VCR.configure do |c|
+ c.ignore_request { |r| true }
+ c.before_http_request { |r| hook_called = true }
+ end
+
+ make_http_request(:get, "http://localhost:#{VCR::SinatraApp.port}/foo")
+ hook_called.should be_false
+ end
+ end
+
describe '.stub_requests using specific match_attributes' do
before(:each) { VCR.stub(:real_http_connections_allowed? => false) }
let(:interactions) { interactions_from('match_requests_on.yml') }

0 comments on commit a8110df

Please sign in to comment.