我有一個控制器,它看起來像這樣API控制器獲取錯誤:鳳凰:無論PARAMS
defmodule PrefectWeb.DocumentController do
use PrefectWeb, :controller
alias Prefect.Queue
def create(conn, params) do
case Prefect.add(Queue, struct(Prefect.Document, params[:id])) do
nil -> conn
|> put_status(404)
|> render("error.json")
status -> {:ok, status}
end
end
end
的創建方法應該添加params[:id]
到Queue
過程。我的單元測試是這樣的:
defmodule PrefectWeb.DocumentControllerTest do
use ExUnit.Case, async: true
use PrefectWeb.ConnCase
setup do
params = [
env: "test",
id: 1,
]
[params: params]
end
test "creation", %{conn: conn, params: params} do
conn
|> post(document_path(conn, :create, params))
assert json_response(conn, 422)
end
end
該規範返回此錯誤:
1) test creation (PrefectWeb.DocumentControllerTest)
test/prefect_web/controllers/document_controller_test.exs:27
** (Protocol.UndefinedError) protocol Enumerable not implemented for nil. This protocol is implemented for: Date.Range, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Range, Stream
如果我改變控制器功能給他:
def create(conn, %{"params" => params}) do
...
end
我得到這個錯誤:
1) test creation (PrefectWeb.DocumentControllerTest)
test/prefect_web/controllers/document_controller_test.exs:27
** (Phoenix.ActionClauseError) could not find a matching PrefectWeb.DocumentController.create clause
to process request. This typically happens when there is a
parameter mismatch but may also happen when any of the other
action arguments do not match. The request parameters are:
%{"env" => "test", "id" => "1"}
爲什麼我不能通過params[:id]
正確的創建方法?
更新
添加請求頭並沒有幫助:
|> put_req_header("content-type", "application/json")
啊!謝謝。哈,這有點讓人困惑。 –