Class: Faraday::Adapter::Test
- Inherits:
-
Faraday::Adapter
- Object
- Middleware
- Faraday::Adapter
- Faraday::Adapter::Test
- Defined in:
- lib/faraday/adapter/test.rb
Overview
Examples
test = Faraday::Connection.new do
use Faraday::Adapter::Test do |stub|
# simply 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
# regular expression can be used as matching filter
stub.get /\A\/items\/(\d+)\z/ do |env, |
# in case regular expression is used an instance of MatchData can be received
[200, {'Content-Type' => 'text/plain'}, "showing item: #{[:match_data][1]}"]
end
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'
Defined Under Namespace
Constant Summary
Constants inherited from Faraday::Adapter
Instance Attribute Summary collapse
-
#stubs ⇒ Object
Returns the value of attribute stubs.
Attributes included from Parallelism
Instance Method Summary collapse
- #call(env) ⇒ Object
- #configure {|stubs| ... } ⇒ Object
-
#initialize(app, stubs = nil, &block) ⇒ Test
constructor
A new instance of Test.
Methods inherited from Faraday::Adapter
Methods included from Parallelism
#inherited, #supports_parallel?
Methods included from Faraday::AutoloadHelper
#all_loaded_constants, #autoload_all, #load_autoloaded_constants
Methods inherited from Middleware
dependency, inherited, loaded?, new
Methods included from MiddlewareRegistry
#fetch_middleware, #load_middleware, #lookup_middleware, #middleware_mutex, #register_middleware
Constructor Details
Instance Attribute Details
#stubs ⇒ Object
Returns the value of attribute stubs.
40 41 42 |
# File 'lib/faraday/adapter/test.rb', line 40 def stubs @stubs end |
Instance Method Details
#call(env) ⇒ Object
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/faraday/adapter/test.rb', line 184 def call(env) super normalized_path = Faraday::Utils.normalize_path(env[:url]) params_encoder = env.request.params_encoder || Faraday::Utils.default_params_encoder stub, = stubs.match(env[:method], normalized_path, env.request_headers, env[:body]) if stub env[:params] = (query = env[:url].query) ? params_encoder.decode(query) : {} block_arity = stub.block.arity status, headers, body = (block_arity >= 0) ? stub.block.call(*[env, ].take(block_arity)) : stub.block.call(env, ) save_response(env, status, body, headers) else raise Stubs::NotFound, "no stubbed request for #{env[:method]} #{normalized_path} #{env[:body]}" end @app.call(env) end |
#configure {|stubs| ... } ⇒ Object
180 181 182 |
# File 'lib/faraday/adapter/test.rb', line 180 def configure yield(stubs) end |