存根Guardian.Plug.EnsureAuthenticated for Phoenix Controller测试

时间:2016-06-01 00:40:53

标签: elixir phoenix-framework

我的路由器管道中有Guardian.Plug.EnsureAuthenticated。如何在Controller测试期间通过它?

2 个答案:

答案 0 :(得分:5)

我获得了Phoenix授权控制器测试通过。这是我的解决方案:

<强>测试/控制器/ inbox_controller_test.exs:

defmodule MyApp.InboxControllerTest do
  use MyApp.ConnCase
  alias MyApp.User

  setup do
    user = %User{id: "a1234"}
    {:ok, jwt, full_claims} = Guardian.encode_and_sign(user)
    {:ok, %{user: user, jwt: jwt, claims: full_claims}}
  end

  test "lists all entries on index", %{jwt: jwt} do
    conn = conn()
      |> put_req_header("authorization", "Bearer #{jwt}")
      |> get(inbox_path(conn, :index))
    assert json_response(conn, 200)["inboxes"] == []
  end
end

<强>配置/ test.exs:

config :guardian, Guardian,
  serializer: MyApp.TestGuardianSerializer

<强>测试/支持/ test_guardian_serializer.ex:

defmodule MyApp.TestGuardianSerializer do
  @behaviour Guardian.Serializer

  alias MyApp.User

  def for_token(user = %User{}), do: { :ok, "User:#{user.id}" }
  def for_token(_), do: { :error, "Unknown resource type" }

  def from_token("User:" <> id) do
    {:ok, %User{id: id, login: "admin"}}
  end

  def from_token(_), do: { :error, "Unknown resource type" }
end

答案 1 :(得分:5)

我通过创建一个测试标记来解决这个问题,该标记使用Guardian的sign_in方法创建并记录用户(如果在Guardian 0.14.x上使用api_sign_in)。然后,您可以将其应用于需要登录用户的测试,如下所示:

  setup %{conn: conn} = config do
    cond do
      config[:login] ->
        user = insert_user()
        signed_conn = Guardian.Plug.sign_in(conn, user)
        {:ok, conn: signed_conn}
      true ->
        :ok
    end
  end

  @tag :login
  test "shows page only when logged in", %{conn: conn} do
    conn = get(conn, some_page_path(conn, :index))
    assert html_response(conn, 200)
  end

如果您需要刚刚为断言创建的用户,可以将其与连接一起传递:

 config[:login] ->
   user = insert_user()
   signed_conn = Guardian.Plug.sign_in(conn, user)
   {:ok, conn: signed_conn, user: user}

在测试中进行模式匹配:

  @tag :login
  test "shows page only when logged in", %{conn: conn, user: user} do
    # ...
  end

考虑将insert_user逻辑移到setup_all块以减少数据库操作并加快测试速度。