October 12, 2015

Today, I learned:
How to replace Faraday middleware

When using Faraday for testing you can use its built-in test adapter which lets you stub HTTP responses for the URLs that you specify. I learned today that if you already have an adapter registered, say the Faraday::Adapter::NetHttp adapter, you need to remove it from the builder or else you will have unexpected behavior when making fake HTTP calls.

You can remove the previous adapter from the builder like such:

# A module to generate a client with a base URL and adapter
module API

  def self.client(api_url)
    Faraday.new(:url => api_url) do |faraday|
      faraday.use      Faraday::Response::RaiseError
      faraday.request  :url_encoded             
      faraday.adapter  Faraday.default_adapter  
      faraday.headers['Content-Type'] = 'application/json'


let(:fake_faraday) {
  client = API.client('http://fake.host:8080')
  # Remove the default NetHttp adapter before adding the test adapter
  client.adapter :test, http_stubs

let(:http_stubs) { Faraday::Adapter::Test::Stubs.new }
Filed under: