I have a basic application and tried to use plugs on my controller. It should basically return 400 if the request body doesn't have "url" parameter. It works fine when I send a request from Postman but it seems it doesn't work on my tests.
Do I have to do anything for it to work also in test environment?
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:
test "returns an error without a url", %{ conn: conn } do
response =
conn
|> post("/shorten", %{})
|> json_response(400)
assert response["errors"] != %{}
end
Result:
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)
Postman Result: https://prnt.sc/qdy2bo