gpt4 book ai didi

elixir - 使用 Guardian 进行 Controller 测试

转载 作者:行者123 更新时间:2023-12-04 01:56:56 27 4
gpt4 key购买 nike

我在我的应用程序中有经过身份验证的路由,现在我开始使用 Controller 测试这些端点。但我首先需要授权我的请求,然后才能测试 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

所以我试图在我的 LeagueController 中点击 create 路径。但是我遇到了身份验证错误,因为不记名 header 中没有 jwt。

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

最佳答案

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

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

关于elixir - 使用 Guardian 进行 Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49949214/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com