Testing a controller that makes outside api calls

Sure. Bear in mind I’m new to most of this, so I might easily have missed something. But AFAIK I can’t put the bypassed url into the compile time test config (ie. config/test.exs), as I can’t get the port from bypass until runtime.

My initial approach was to try something like this in my ExUnit Case:


setup do

  bypass = Bypass.open()

  url = "http://localhost:#{bypass.port}"

  Application.put_env(:app, :api_endpoint, url)

 

  Bypass.stub(bypass, "GET", "/checklists/1.json", fn conn ->

    Plug.Conn.resp(conn, 200, TestData.Load.list())

  end)

  {:ok, %{api_token: "token"}}

end

… and then get the url out of the Application config in my API client module.

The problem here is that with the tests running async, the global :api_endpoint config writes get interleaved unpredictably, so the client module requests go to the wrong ports & hence wrong stubs. The result is failing tests due to unexpected or no responses. Async and global rarely mix well …

This is the same issue axelson refers to here: Bypass and async tests with ex_unit - #3 by axelson

(Presumably, as you haven’t had any such problems, your setup must be a bit different from the above.)

1 Like