Method: Typhoeus.stub

Defined in:
lib/typhoeus.rb

.stub(base_url, options = {}, &block) ⇒ Typhoeus::Expectation

Stub out a specific request.

Examples:

Stub a request and get specified response.

expected = Typhoeus::Response.new
Typhoeus.stub("www.example.com").and_return(expected)

actual = Typhoeus.get("www.example.com")
expected == actual
#=> true

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") do
  actual_widgets = Widget.all
  Typhoeus::Response.new(
    :body => actual_widgets.inject([]) do |ids, widget|
      ids << widget.id
    end.join(",")
  )
end

Stub a request and get a lazily-constructed response in the format requested.

Typhoeus.stub("www.example.com") do |request|
  accept = (request.options[:headers]||{})['Accept'] || "application/json"
  format = accept.split(",").first
  body_obj = { 'things' => [ { 'id' => 'foo' } ] }

  Typhoeus::Response.new(
    :headers => {
      'Content-Type' => format
    },
    :body => SERIALIZERS[format].serialize(body_obj)
  )
end

Parameters:

  • base_url (String)

    The url to stub out.

  • options (Hash) (defaults to: {})

    The options to stub out.

Returns:

See Also:

Since:

  • 0.5.0


90
91
92
93
94
95
96
97
98
99
# File 'lib/typhoeus.rb', line 90

def self.stub(base_url, options = {}, &block)
  expectation = Expectation.all.find{ |e| e.base_url == base_url && e.options == options }
  if expectation.nil?
    expectation = Expectation.new(base_url, options)
    Expectation.all << expectation
  end

  expectation.and_return(&block) unless block.nil?
  expectation
end