使用 Guardian 进行控制器测试

Bit*_*ise 3 elixir jwt phoenix-framework guardian

我已经在我的应用程序中验证了路由,现在我开始使用控制器测试这些端点。但我首先需要授权我的请求,然后才能测试 API 端点。这是我的测试:

  setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
  end

  test "creates and renders resource when data is valid", %{conn: conn} do
    conn = post(conn, league_path(conn, :create), league: @valid_attrs)
    body = json_response(conn, 201)
    assert body["name"]
    assert Repo.get_by(League, name: "Obama's League")
  end 
Run Code Online (Sandbox Code Playgroud)

当我尝试运行该测试时,出现以下错误:

expected response with status 201, got: 401, with body:
 {"errors":["Unauthenticated"]}
Run Code Online (Sandbox Code Playgroud)

路由器:

pipeline :authenticated do
  plug(Guardian.Plug.EnsureAuthenticated)
end

scope "/api/v1", Statcasters do
  pipe_through([:api, :authenticated])

  resources("/users", UserController, except: [:create])
  resources("/leagues", LeagueController, only: [:create])
end
Run Code Online (Sandbox Code Playgroud)

所以我试图create在我的 LeagueController 中找到路径。但我遇到了身份验证错误,因为我的承载标头中没有 jwt。

如何生成令牌以及如何在测试前设置它?

The*_*Anh 5

假设您有一个用户资源需要进行身份验证,那么您可以像这样设置它:

setup %{conn: conn} do
    user = # Your user resource
    {:ok, jwt, _claims} = Guardian.encode_and_sign(user)
    conn =
      conn
      |> put_req_header("accept", "application/json")
      |> put_req_header("authorization", "Bearer #{jwt}")

    {:ok, conn: conn}
  end
Run Code Online (Sandbox Code Playgroud)