Sha256: c89c799718e7c09b56800914fe2a2361d91b0a4b035bcf1ea5c87c3bc65ec486

Contents?: true

Size: 1.41 KB

Versions: 4

Compression:

Stored size: 1.41 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

4 entries across 4 versions & 1 rubygems

Version Path
npr-3.0.0 spec/support/fake_response.rb
npr-2.0.2 spec/support/fake_response.rb
npr-2.0.1 spec/support/fake_response.rb
npr-2.0.0 spec/support/fake_response.rb