Skip to content

Commit

Permalink
Accepting the lazy response construction block of a stubbed request o…
Browse files Browse the repository at this point in the history
…n the call to Typhoeus.stub
  • Loading branch information
ryankinderman committed Mar 9, 2013
1 parent d378933 commit ac18808
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
12 changes: 7 additions & 5 deletions lib/typhoeus.rb
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions lib/typhoeus/expectation.rb
Expand Up @@ -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|
Expand All @@ -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' } ] }
Expand Down
17 changes: 17 additions & 0 deletions spec/typhoeus_spec.rb
Expand Up @@ -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
Expand All @@ -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 }

Expand Down

0 comments on commit ac18808

Please sign in to comment.