我有一个看起来像这样的控制器:
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
create方法应该将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]
传递给create方法?
更新
添加请求标头也无济于事:
|> put_req_header("content-type", "application/json")
答案 0 :(得分:1)
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
和你的考试
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 :(得分:0)
您在setup
创建的conn上声明,而不是从post
返回的conn。尝试在断言之前重新绑定conn
。
test "creation", %{conn: conn, params: params} do
conn =
conn
|> post(document_path(conn, :create), params)
assert json_response(conn, 422)
end