Skip to content

Instantly share code, notes, and snippets.

@simeonwillbanks
Last active January 25, 2023 17:49
Show Gist options
  • Save simeonwillbanks/3e7650da9c9603a936114704e1819e98 to your computer and use it in GitHub Desktop.
Save simeonwillbanks/3e7650da9c9603a936114704e1819e98 to your computer and use it in GitHub Desktop.
Faraday, Minitest, and VCR
# frozen_string_literal: true
require "faraday"
require "faraday/retry"
require "httpx/adapters/faraday"
module App
class Client
def connection
Faraday.new(url) do |f|
# https://github.com/lostisland/faraday-retry#usage
# Retry transient failures
# By default, it retries 2 times and handles only timeout exceptions
f.request :retry
# https://lostisland.github.io/faraday/middleware/authentication
# Automatically add an Authorization header to your requests
f.request :authorization, "Bearer", -> { auth_token }
f.request :json # encode req bodies as JSON and automatically set the Content-Type header
f.response :json # decode response bodies as JSON
# https://lostisland.github.io/faraday/middleware/raise-error
# If an HTTP response returns with a 4xx or 5xx status code
# the RaiseError middleware raises a Faraday::Error exception
f.response :raise_error
# https://gitlab.com/os85/httpx#what-makes-it-the-best-ruby-http-client
# https://os85.gitlab.io/httpx/
# https://os85.gitlab.io/httpx/wiki/home.html
f.adapter :httpx
end
end
private
def auth_token
ENV["AUTH_TOKEN"]
end
def url
"https://example.com"
end
end
end
# frozen_string_literal: true
module App
class Resource
attr_reader :connection
def initialize(connection: Client.new.connection)
@connection = connection
end
def get(id:)
connection.get("/resources/#{id}")
end
end
end
# frozen_string_literal: true
require "test_helper"
class TestAppResource < Minitest::Test
def setup
@resource = App::Resource.new
end
def test_get
VCR.use_cassette("test_get") do
id = 1
response = @resource.get(id: id)
assert_equal id, response.body["id"]
end
end
end
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "app"
require "minitest/autorun"
require "vcr"
VCR.configure do |c|
c.cassette_library_dir = "test/vcr"
c.hook_into :faraday
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment