我是 Phoenix 的新手,我正在测试一个自定义插件,如果不满足条件,它应该重定向到/404.html 页面。当我尝试成功/失败路径时,代码可以正常工作,但我很难理解为什么我的测试方法会失败。
测试失败归结为以下几点:
%Plug.Conn{} |> Phoenix.Controller.redirect(to: "/404.html")
我的期望是这应该返回一个
conn
然后我可以在其上运行断言的对象。但是,当我尝试运行上述代码时,出现以下错误:** (UndefinedFunctionError) function Plug.Conn.send_resp/4 is undefined or private. Did you mean one of:
这有点奇怪,因为 Phoenix.Controller 模块实现了
send_resp/4
函数并在其定义的顶部导入 Plug.Conn。为什么它忽略该功能并试图点击
Plug.Conn
直接地?我不是在调用该私有(private)函数,而是将一个公共(public)函数委托(delegate)给它,除非我遗漏了一些明显的东西,否则它应该是洁净的。这个问题有简单的解决方案还是我应该采取另一种方法?编辑
这是来自 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
redirect
函数的实现可以在这里找到:https://github.com/phoenixframework/phoenix/blob/v1.2.3/lib/phoenix/controller.ex#L297
send_resp
我希望它达到的功能可以在这里找到:https://github.com/phoenixframework/phoenix/blob/v1.2.3/lib/phoenix/controller.ex#L748
最佳答案
正如 Stacktrace 的第一行所示。 nil
是 Plug.Conn.send_resp/4
的第一个参数功能。 Plug.Conn.send_resp/4
虽然功能不存在。如您在 the docs 中所见,只有一元和三元在code .
您可能将它与 Phoenix.Controller.send_resp/4
混淆了。像你链接它一样发挥作用。
尽管如此,主要问题是 nil
传递给 send_resp
对任何一个功能都不起作用的功能。似乎 conn 在某个地方丢失了。
因此我建议使用@Dogbert 的评论并使用Phoenix.ConnTest.build_conn()
模拟一个 conn 而不是用 %Plug.Conn{}
初始化一个空的 conn 结构.
关于elixir - 测试 Phoenix.Controller.redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43272984/