我有一个基本应用程序并尝试在我的控制器上使用插件。如果请求正文没有“url”参数,它基本上应该返回 400。当我从邮递员发送请求时它工作正常,但它似乎不适用于我的测试。
我是否必须做任何事情才能使其在测试环境中也能正常工作?
plug :check_url_existence when action in [:create]
def create(conn, link_params) do
with {:ok, %Link{} = link} <- Links.create_link(link_params) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.link_path(conn, :show, link))
|> render("show.json", link: link)
end
end
defp check_url_existence(conn, _) do
if is_nil(conn.params["url"]) do
conn
|> put_status(:bad_request)
|> put_view(ShortyWeb.ErrorView)
|> render("400.json")
end
conn
end
测试:
test "returns an error without a url", %{ conn: conn } do
response =
conn
|> post("/shorten", %{})
|> json_response(400)
assert response["errors"] != %{}
end
结果:
1) test shortcode generation returns an error without a url (ShortyWeb.LinkControllerTest)
test/shorty_web/controllers/link_controller_test.exs:58
** (RuntimeError) expected response with status 400, got: 422, with body:
{"errors":{"url":["can't be blank"]}}
code: |> json_response(400)
stacktrace:
(phoenix) lib/phoenix/test/conn_test.ex:373: Phoenix.ConnTest.response/2
(phoenix) lib/phoenix/test/conn_test.ex:419: Phoenix.ConnTest.json_response/2
test/shorty_web/controllers/link_controller_test.exs:62: (test)
邮递员结果: https ://prnt.sc/qdy2bo