您好我正在尝试通过此测试
test "authentication plug should return 401 when not authenticated", %{conn: conn} do
conn = Map.put(conn, :params, %{})
conn = ChaacServerWeb.Plugs.Authentication.call(conn, nil)
assert json_response(conn, 401)["errors"] != %{}
end
这是我的插件
def call(conn, _) do
token = List.first(get_req_header(conn, "authorization"))
case Accounts.validate_token(conn.params["user_id"], token) do
{:ok, valid_token} -> conn
err ->
conn
|> halt()
|> ChaacServerWeb.FallbackController.call(err)
end
end
我收到此错误
1) test authentication plug should return 401 when not authenticated (ChaacServerWeb.AuthenticationTest) test/chaac_server_web/plugs/authentication_test.exs:26
** (RuntimeError) cannot render template :"401" because conn.params["_format"] is not set.
Please set `plug :accepts, ~w(html json ...)` in your pipeline.
code: conn = ChaacServerWeb.Plugs.Authentication.call(conn, nil)
stacktrace:
(phoenix) lib/phoenix/controller.ex:689: Phoenix.Controller.render/3
test/chaac_server_web/plugs/authentication_test.exs:28: (test)
我知道我需要在我的测试设置中以某种方式调用plug :accepts, [:json]
但是我该怎么做?谢谢
(编辑)我的路由器在我的管道中有plug :accepts, [:json]
答案 0 :(得分:0)
我刚刚做了
test "authentication plug should return 401 when not authenticated", %{conn: conn} do
conn = Map.put(conn, :params, %{"_format" => "json"})
conn = ChaacServerWeb.Plugs.Authentication.call(conn, nil)
assert json_response(conn, 401)["errors"] != %{}
end
感觉abit hacky但它对我有用。
答案 1 :(得分:0)
您可以使用put_req_header
:
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end