Phoenix.Controller.redirect testing
I am new to Phoenix and I am testing a custom Plug that should redirect to /404.html page if the condition is not met. The code works correctly when I try to use the success / failure paths, but I have a hard time understanding why my testing approach explodes.
The test failure boils down to the following:
%Plug.Conn{} |> Phoenix.Controller.redirect(to: "/404.html")
My expectation is that this should return an object conn
, which I can then run. However, when I try to run the above code, I get the following error:
** (UndefinedFunctionError) function Plug.Conn.send_resp/4 is undefined or private. Did you mean one of:
This is a little weird as the Phoenix.Controller module implements the function send_resp/4
and it imports Plug.Conn at the top of its definition.
Why is it ignoring this function and trying to push Plug.Conn
directly? I am not calling this private function, the public function delegates to it, which should be kosher, unless I missed something obvious. Is there an easy solution to this problem or should I use a different approach?
EDIT
Here is the complete stack trace from iex:
%Plug.Conn{} |> Phoenix.Controller.redirect(to: "/404.html")
** (UndefinedFunctionError) function Plug.Conn.send_resp/4 is undefined or private. Did you mean one of:
* send_resp/1
* send_resp/3
(plug) Plug.Conn.send_resp(nil, 302, [{"content-type", "text/html; charset=utf-8"}, {"cache-control", "max-age=0, private, must-revalidate"}, {"location", "/404.html"}], "<html><body>You are being <a href=\"/404.html\">redirected</a>.</body></html>")
(plug) lib/plug/conn.ex:393: Plug.Conn.send_resp/1
The function implementation redirect
can be found here:
https://github.com/phoenixframework/phoenix/blob/v1.2.3/lib/phoenix/controller.ex#L297
The feature send_resp
I am expecting can be found here:
https://github.com/phoenixframework/phoenix/blob/v1.2.3/lib/phoenix/controller.ex#L748
source to share
As the first line of your Stacktrace shows. nil
is the first argument to the function Plug.Conn.send_resp/4
. The function Plug.Conn.send_resp/4
does not exist. Only arity one and three, as you can see in the docs in the code .
You probably confused this with Phoenix.Controller.send_resp/4
when you tied it.
However, the main problem is that it nil
is passed into a function send_resp
that will not work for any function. Conn seems to have been lost somewhere.
So I suggest going with @ Dogbert's comment and using Phoenix.ConnTest.build_conn()
that Phoenix.ConnTest.build_conn()
instead of initializing an empty struct %Plug.Conn{}
with %Plug.Conn{}
.
source to share