Skip to content

Instantly share code, notes, and snippets.

@brentonannan
Created November 9, 2015 00:27
Show Gist options
  • Save brentonannan/5f3150b99f4f73973bc0 to your computer and use it in GitHub Desktop.
Save brentonannan/5f3150b99f4f73973bc0 to your computer and use it in GitHub Desktop.
Creating a mock HTTPoison client
defmodule Client do
# This doesn't work!
use Application.get_env(:my_app, :http_client_base, HTTPoison.Base)
defp process_url(url) do
url |> URI.parse |> Map.put(:scheme, "https") |> URI.to_string
end
defp process_request_body(body) do
body
end
defp process_request_headers(headers) do
headers
end
end
defmodule ClientTest do
use ExUnit.Case
doctest Client
test "uses Test.HTTPClient.Base" do
assert %{method: :get, url: _, body: _, headers: _} = Client.get("http://example.com")
end
test "upgrades url to https" do
assert %{method: :get, url: "https://example.com", body: _, headers: _} = Client.get("http://example.com")
end
end
# Emulates HTTPoison.Base but returns request maps instead of doing anything
defmodule Test.HTTPClient.Base do
defmacro __using__(_) do
quote do
def get(url, headers \\ [], options \\ []) do
request(:get, url, "", headers, options)
end
def request(method, url, body \\ "", headers \\ [], options \\ []) do
%{
method: method,
url: process_url(url),
body: process_request_body(body),
headers: process_request_headers(headers),
}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment