Permalink
Browse files

Accepting the lazy response construction block of a stubbed request o…

…n the call to Typhoeus.stub
  • Loading branch information...
1 parent d378933 commit ac18808dc60de86b8ba7118e4f7140b5bd17cb23 @ryankinderman ryankinderman committed Mar 9, 2013
Showing with 26 additions and 7 deletions.
  1. +7 −5 lib/typhoeus.rb
  2. +2 −2 lib/typhoeus/expectation.rb
  3. +17 −0 spec/typhoeus_spec.rb
View
@@ -73,13 +73,15 @@ def configure
# @return [ Typhoeus::Expectation ] The expecatation.
#
# @see Typhoeus::Expectation
- def stub(base_url, options = {})
+ def stub(base_url, options = {}, &block)
expectation = Expectation.all.find{ |e| e.base_url == base_url && e.options == options }
- return expectation if expectation
-
- Expectation.new(base_url, options).tap do |new_expectation|
- Expectation.all << new_expectation
+ if expectation.nil?
+ expectation = Expectation.new(base_url, options)
+ Expectation.all << expectation
end
+
+ expectation.and_return &block unless block.nil?
+ expectation
end
# Add before callbacks.
@@ -16,7 +16,7 @@ module Typhoeus
# #=> true
#
# @example Stub a request and get a lazily-constructed response containing data from actual widgets that exist in the system when the stubbed request is made.
- # Typhoeus.stub("www.example.com/widgets").and_return do
+ # Typhoeus.stub("www.example.com/widgets") do
# actual_widgets = Widget.all
# Typhoeus::Response.new(
# :body => actual_widgets.inject([]) do |ids, widget|
@@ -26,7 +26,7 @@ module Typhoeus
# end
#
# @example Stub a request and get a lazily-constructed response in the format requested.
- # Typhoeus.stub("www.example.com").and_return do |request|
+ # Typhoeus.stub("www.example.com") do |request|
# accept = (request.options[:headers]||{})['Accept'] || "application/json"
# format = accept.split(",").first
# body_obj = { 'things' => [ { 'id' => 'foo' } ] }
View
@@ -21,7 +21,22 @@
describe ".stub" do
let(:base_url) { "www.example.com" }
+ shared_examples "lazy response construction" do
+ it "calls the block to construct a response when a request matches the stub" do
+ expected_response = Typhoeus::Response.new
+ Typhoeus.stub(base_url) do |request|
+ expected_response
+ end
+
+ response = Typhoeus.get(base_url)
+
+ expect(response).to be(expected_response)
+ end
+ end
+
context "when no similar expectation exists" do
+ include_examples "lazy response construction"
+
it "returns expectation" do
expect(Typhoeus.stub(base_url)).to be_a(Typhoeus::Expectation)
end
@@ -33,6 +48,8 @@
end
context "when similar expectation exists" do
+ include_examples "lazy response construction"
+
let(:expectation) { Typhoeus::Expectation.new(base_url) }
before { Typhoeus::Expectation.all << expectation }

0 comments on commit ac18808

Please sign in to comment.