如何测试与Phoenix重定向一起设置404状态的插头

时间:2019-02-21 21:57:27

标签: elixir phoenix-framework plug

我试图测试以下插件在找不到site_id时是否返回404。一切都可以在浏览器中运行,但是测试会引发异常。

我的插头:

defmodule MyWeb.Plugs.GetSite do
  import Plug.Conn

  def init(default), do: default

  def call(%Plug.Conn{host: host} = conn, _default) do
    case GetSite.get_site_id(host) do
      nil -> redirect_to_404(conn)
      id -> assign(conn, :site_id, id)
    end
  end

  defp redirect_to_404(conn) do
    conn
    |> put_status(:not_found)
    |> Phoenix.Controller.put_view(MyWeb.ErrorView)
    |> Phoenix.Controller.render(:"404")
    |> halt()
  end
end

我的测试当前看起来像:

test "user is redirected to 404 if no matching site_id is found" do
  conn =
    Phoenix.ConnTest.build_conn(:get, "http://unknown.local")
    |> MyWeb.Plugs.GetSite.call(%{})

  assert conn.status == 404
end

这是我得到的例外:

(plug) lib/plug/conn/unfetched.ex:35: Plug.Conn.Unfetched.raise_unfetched/3
(elixir) lib/access.ex:322: Access.get/3
(phoenix) lib/phoenix/controller.ex:680: Phoenix.Controller.render/3

这里的最佳做法是什么?我应该在插头中呼唤Phoenix吗?任何帮助或建议都非常好。

谢谢。

0 个答案:

没有答案