我已经在我的应用程序中验证了路由,现在我开始测试这些端点的控制器。但我首先需要授权我的请求,然后才能测试 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"]}
路由器:
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
所以我试图在我的联盟控制器中走create
路。但是我遇到了身份验证错误,因为我在持有者标头中没有 jwt。
如何生成令牌以及如何在测试前进行设置?
假设您有一个要进行身份验证的用户资源,那么您可以像这样设置它:
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