Sha256: 2ae5beb767dbdc72355fa951f0ee48f94803e1f540e78c0e6d29eb1cfc86b692

Contents?: true

Size: 1.43 KB

Versions: 2

Compression:

Stored size: 1.43 KB

Contents

##
# FakeResponse
#
# Helpers for faking responses from the API
#
module FakeResponse
  #---------------------
  # Takes the filename to respond with,
  # and (optionally) any options to be passed to 
  # +FakeWeb.register_uri+.
  #
  # If no block is given, the registry will not be cleaned
  # by this method.
  #
  # If passed a block, it will clean the registry after
  # the block has been run.
  #
  def mock_response(filename, options={}, &block)
    respond_with(filename, options)
    
    response = yield
    FakeWeb.clean_registry
    
    response
  end

  #---------------------
  # Register the NPR root with FakeWeb, and set its 
  # response body to the contents of the requested file.
  def respond_with(filename, options)
    content_type = options[:content_type] || "application/json"
    uri          = options.delete(:uri) || %r{^#{NPR::Configuration::API_ROOT}}

    FakeWeb.register_uri(:get, uri, 
      { 
        :body         => load_fixture(filename),
        :content_type => content_type
      }.merge(options))
  end
  
  #---------------------
  # Read a fixure file
  def load_fixture(filename)
    file = filename == :random ? random_filename : filename
    File.read(File.join FIXTURE_ROOT, file)
  end
  
  #---------------------
  # Select a random response fixture
  def random_filename
    filename = Dir["#{FIXTURE_ROOT}/**/*story*.*"].sample
    puts "Responding with #{filename}"
    filename
  end
end # FakeResponse

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
npr-1.2.0 spec/support/fake_response.rb
npr-1.1.0 spec/support/fake_response.rb