Background
I have a controller that receives Plug requests via it’s process
function. My objective is to test said function, without the need to perform a GET request.
Code
To achieve this I am calling the function directly. Following is the said function:
@spec process(Conn.t, keyword) :: Conn.t
def process(%Conn{} = conn, deps) do
query_params =
conn
|> Conn.fetch_query_params()
|> Map.get(:query_params)
|> Map.delete("format")
with {:ok, results} <- deps[:search].(query_params),
{:ok, answer} <- deps[:format].(results, "json")
do
Conn.send_resp(conn, Status.code(:ok), answer)
else
{:error, :json_encoding_failed, err} ->
Conn.send_resp(conn, Status.code(:unprocessable_entity), "Failed to JSON enconde query results: #{inspect err}")
{:error, :invalid_format, inv_format} ->
Conn.send_resp(conn, Status.code(:bad_request), "Invalid format specified: #{inspect inv_format}")
end
end
My objective is to, by being able to call this function with injected dependencies, to simulate the errors json_encoding_failed
and invalid_format
.
Problem
The problem is that I still need to pass this function a Plug.Conn
object. Now, this controller is really dummy, all it does is run 2 functions and handle the errors, so I don’t think I can abstract any logic from here)
So test this I need to pass in a dummy Plug.Conn
object. But the code I am using doesn’t work:
conn = %Conn{}
Search.process(conn, deps)
It blows with the following error:
** (UndefinedFunctionError) function Plug.MissingAdapter.send_resp/4 is undefined (module Plug.MissingAdapter is not available)
Questions
- Is this the correct approach to testing my controller? I think I can’t extract more logic from there.
- Why am I getting this error? How can I create a dummy
Plug.Conn
object?