Skip to content

Instantly share code, notes, and snippets.

@ardell
Created February 11, 2016 17:58
Show Gist options
  • Save ardell/b89872f7d2137e0f3d58 to your computer and use it in GitHub Desktop.
Save ardell/b89872f7d2137e0f3d58 to your computer and use it in GitHub Desktop.
defmodule GeocodingAdapter.GoogleMaps do
defmodule UnparseableResponse do
defexception message: "Received a response from Google Maps that contained invalid json"
end
def geocode(address) do
fetch_response
|> return_empty_unless_success
|> parse_body
end
defp fetch_response do
response = HTTPotion.get("http://foo.com/bar/baz.json")
{ :ok, response }
end
defp return_empty_unless_success({ :ok, response }) do
if response[:status_code] == 200 do
{ :ok, response }
else
{ :error, [] }
end
end
defp return_empty_unless_success({ _, response }) do
response
end
defp parse_body({ :ok, response }) do
try do
Poison.decode!(response[:body])
rescue
Poison.SyntaxError -> raise UnparseableResponse
end
end
defp parse_body({ _, response }) do
response
end
end
defmodule GeocodingAdapter.GoogleMapsTest do
use ExSpec
import Mock
setup do
street_number = '888'
route = '3rd St.'
{
:ok,
[
subject: GeocodingAdapter.GoogleMaps,
address: [
name: "Shiplify HQ",
street_address: Enum.join([street_number, route], " "),
city: "Atlanta",
state: "GA",
postal_code: "30318",
],
]
}
end
describe "geocode" do
it "returns empty array when receiving a non-2XX return code from Google's API", context do
{ subject, address } = { context[:subject], context[:address] }
response = %{ status_code: 404 }
with_mock HTTPotion, [get: fn(_url) -> response end] do
assert subject.geocode(address) == []
end
end
it "raises an exception if Google's API returns invalid json", context do
{ subject, address } = { context[:subject], context[:address] }
response = %{ status_code: 200, body: "bad-json" }
with_mock HTTPotion, [get: fn(_url) -> response end] do
assert_raise Module.concat(subject, :UnparseableResponse), fn ->
subject.geocode(address)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment