使用Guardian进行控制器测试

时间:2018-04-20 20:23:32

标签: 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 

当我尝试运行该测试时,我收到此错误:

expected response with status 201, got: 401, with body:
 {"errors":["Unauthenticated"]}

ROUTER:

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

所以我试图点击我的LeagueController中的create路径。但是我遇到了auth错误,因为我在承载标题中没有jwt。

如何在测试之前生成令牌以及如何设置令牌?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

假设您有用户资源进行身份验证,那么您可以这样设置:

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