1

I'm trying to test that the plug below returns a 404 when a site_id is not found. Everything works in the browser but the test throws an exception.

My plug:

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

My test currently looks like:

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

And this is the exception I'm getting:

(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

What is the best practice here? Should I be calling out to Phoenix in my Plugs? Any help or advice would be really great.

Thank you.

Kristian Roebuck
  • 3,209
  • 2
  • 21
  • 29
  • 2
    Is that the entire exception you are getting? That seems really small and without much detail. I think what you are looking for is `Phoenix.Controller.render("404.html")` though. – Justin Wood Feb 21 '19 at 23:32
  • Perfect suggestion, @JustinWood. That simple change made everything work. Thank you. – Kristian Roebuck Feb 21 '19 at 23:44

0 Answers0