class Faraday::Adapter::Test

@example

test = Faraday::Connection.new do
  use Faraday::Adapter::Test do |stub|
    # Define matcher to match the request
    stub.get '/resource.json' do
      # return static content
      [200, {'Content-Type' => 'application/json'}, 'hi world']
    end

    # response with content generated based on request
    stub.get '/showget' do |env|
      [200, {'Content-Type' => 'text/plain'}, env[:method].to_s]
    end

    # A regular expression can be used as matching filter
    stub.get /\A\/items\/(\d+)\z/ do |env, meta|
      # in case regular expression is used, an instance of MatchData
      # can be received
      [200,
       {'Content-Type' => 'text/plain'},
       "showing item: #{meta[:match_data][1]}"
      ]
    end

    # You can set strict_mode to exactly match the stubbed requests.
    stub.strict_mode = true
  end
end

resp = test.get '/resource.json'
resp.body # => 'hi world'

resp = test.get '/showget'
resp.body # => 'get'

resp = test.get '/items/1'
resp.body # => 'showing item: 1'

resp = test.get '/items/2'
resp.body # => 'showing item: 2'

Attributes

stubs[RW]

Public Class Methods

new(app, stubs = nil, &block) click to toggle source
Calls superclass method Faraday::Adapter::new
# File lib/faraday/adapter/test.rb, line 226
def initialize(app, stubs = nil, &block)
  super(app)
  @stubs = stubs || Stubs.new
  configure(&block) if block
end

Public Instance Methods

call(env) click to toggle source

@param env [Faraday::Env]

Calls superclass method Faraday::Adapter#call
# File lib/faraday/adapter/test.rb, line 237
def call(env)
  super

  env.request.params_encoder ||= Faraday::Utils.default_params_encoder
  env[:params] = env.params_encoder.decode(env[:url].query) || {}
  stub, meta = stubs.match(env)

  unless stub
    raise Stubs::NotFound, "no stubbed request for #{env[:method]} "\
                           "#{env[:url]} #{env[:body]}"
  end

  block_arity = stub.block.arity
  status, headers, body =
    if block_arity >= 0
      stub.block.call(*[env, meta].take(block_arity))
    else
      stub.block.call(env, meta)
    end
  save_response(env, status, body, headers)

  @app.call(env)
end
configure() { |stubs| ... } click to toggle source
# File lib/faraday/adapter/test.rb, line 232
def configure
  yield(stubs)
end