I like this idea of configuration through config.exs and test.exs.
Revising the example
Based on your feedback, the new set up for the controller would use the @endpoint attribute and it would return a url based on the environment that it’s in.
controller(revised)
defmodule MyAppWeb.Api.TweetController do
use MyAppWeb, :controller
action_fallback MyAppWeb.Api.FallbackController
@endpoint Application.get_env(:myapp, :url)
def index(conn, params) do
with {:ok, result} <- TwitterClient(@endpoint).post_tweet("Elixir is awesome!") do
render(conn, "show.json", tweet: result)
end
end
end
How do I test this controller in my test controller?
test controller
defmodule MyAppWeb.Api.TweetControllerTest do
use MyAppWeb.ConnCase
# I just need to put this here and it will work??
setup do
bypass = Bypass.open()
{:ok, bypass: bypass}
end
describe "GET /tweet" do
test "success, it sends a tweet", %{conn: conn, bypass: bypass} do
# Is `bypass` being passed here the same bypass
# that is in my config :myapp, TwitterClient, url: BYPASS_ENDPOINT
Bypass.expect(bypass, fn conn ->
conn
|> Plug.Conn.put_resp_header("content-type", "application/json")
|> Plug.Conn.resp(200, %{tweet: "Elixir is awesome"})
end)
# controller
conn = get(conn, "/tweet")
assert json_response(conn, 200) == %{tweet: "Elixir is awesome"}
end
end
end






















