I'm writing a controller function where it will check for a condition ( keyword to be valid ) before either to render a json object or error object if failed.
router.ex
scope "/api", DongNghiaWeb do
pipe_through :api
scope "/tim_kiem" do
get "/tu/:word" , APIWordController, :search_word
[...]
word_controller.ex
def search_word(conn, %{"word" => word}) do
conn
|> check_invalid_keyword(word)
|> render("search.json", words: word |> String.trim |> Words.suggest)
end
defp check_invalid_keyword(conn, keyword) do
unless Words.keyword_valid?(String.trim(keyword)) do
conn
|> put_status(400)
|> json(%{
error: "Invalid keyword"
})
end
conn
end
word_controller_test.ex
test "response error when word is not valid", %{conn: conn} do
response = get(conn,api_word_path(conn, :search_word, "a3d"))
|> json_response(400)
assert response["error"] == "Invalid keyword"
end
When running mix test
, the results will be like so :
** (RuntimeError) expected response with status 400, got: 200, with body: {"data":[]}
But when I try testing with a REST client ( Insomnia, for example ), the json will return to be { error : "Invalid keyword" }
just fine.