0

在我的 Phoenix 应用程序中,我的 Plug 看起来像这样:

defmodule MyApp.Web.Plugs.RequireAuth do
  import Plug.Conn
  import Phoenix.Controller
  import MyApp.Web.Router.Helpers

  def init(_options) do
  end

  def call(conn, _options) do
    if conn.assigns[:user] do
      conn
    else
      conn
      |> put_flash(:error, "You must be logged in")
      |> redirect(to: project_path(conn, :index))
      |> halt()
    end
  end
end

我为它写了测试:

defmodule MyApp.Web.Plugs.RequireAuthTest do
  use MyApp.Web.ConnCase

  import MyApp.Web.Router.Helpers

  alias MyApp.Web.Plugs.RequireAuth
  alias MyApp.Accounts.User

  setup do
    conn = build_conn()

    {:ok, conn: conn}
  end

  test "user is redirected when current user is not set", %{conn: conn} do
    conn = RequireAuth.call(conn, %{})

    assert redirected_to(conn) == project_path(conn, :index)
  end

  test "user is not redirected when current user is preset", %{conn: conn} do
    conn = conn
    |> assign(:user, %User{})
    |> RequireAuth.call(%{})

    assert conn.status != 302
  end
end

当我运行我的规格时,它会返回以下错误:

  1) test user is redirected when current user is not set (MyApp.Web.Plugs.RequireAuthTest)
     test/lib/web/plugs/require_auth_test.exs:15
     ** (ArgumentError) flash not fetched, call fetch_flash/2
     stacktrace:
       (phoenix) lib/phoenix/controller.ex:1231: Phoenix.Controller.get_flash/1
       (phoenix) lib/phoenix/controller.ex:1213: Phoenix.Controller.put_flash/3
       (my_app) lib/my_app/web/plugs/require_auth.ex:14: MyApp.Web.Plugs.RequireAuth.call/2
       test/lib/web/plugs/require_auth_test.exs:16: (test)

当我从插头中删除这条线时:

put_flash(:error, "You must be logged in")

规范通过没有问题。我做错了什么?

4

1 回答 1

3

您的示例在凤凰编程中进行了描述,解决方案是使用来自 Phoenix.ConnTest的bypass_through/3绕过路由器层。

在您的测试套件中使用类似的东西:

setup %{conn: conn} do
  conn =
    conn
    |> bypass_through(Rumbl.Router, :browser)
    |> get("/")
  {:ok, %{conn: conn}}
end

它将为您提供有效的闪存和会话支持。

于 2017-03-18T15:07:46.683 回答