我对控制器的测试失败了,我无法弄清楚这个错误的根源。我尝试了所有我能想到的东西,因为错误信息非常通用,所以我有点无助。
有问题的错误消息(运行测试时)。
1) test does not create resource and renders errors when data is invalid (MyApp.AdminControllerTest)
test/controllers/admin_controller_test.exs:21
** (FunctionClauseError) no function clause matching in MyApp.AdminControllerTest.__ex_unit_setup_1/1
stacktrace:
test/controllers/admin_controller_test.exs:8: MyApp.AdminControllerTest.__ex_unit_setup_1(%{async: false, case: MyApp.AdminControllerTest, file: "~/MyApp/test/controllers/admin_controller_test.exs", line: 21, test: :"test does not create resource and renders errors when data is invalid"})
test/controllers/admin_controller_test.exs:1: MyApp.AdminControllerTest.__ex_unit__/2
2) test creates and renders resource when data is valid (MyApp.AdminControllerTest)
test/controllers/admin_controller_test.exs:12
** (FunctionClauseError) no function clause matching in MyApp.AdminControllerTest.__ex_unit_setup_1/1
stacktrace:
test/controllers/admin_controller_test.exs:8: MyApp.AdminControllerTest.__ex_unit_setup_1(%{async: false, case: MyApp.AdminControllerTest, file: "~/MyApp/test/controllers/admin_controller_test.exs", line: 12, test: :"test creates and renders resource when data is valid"})
test/controllers/admin_controller_test.exs:1: MyApp.AdminControllerTest.__ex_unit__/2
我的代码:
admin_controller_test.exs
defmodule MyApp.AdminControllerTest do
use MyApp.ConnCase
alias MyApp.Admin
@valid_attrs %{email: "foo@bar.com", password: "s3cr3t"}
@invalid_attrs %{}
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "creates and renders resource when data is valid", %{conn: conn} do
conn = post conn, admin_path(conn, :create), admin: @valid_attrs
body = json_response(conn, 201)
assert body["data"]["id"]
assert body["data"]["email"]
refute body["data"]["password"]
assert Repo.get_by(Admin, email: "foo@bar.com")
end
test "does not create resource and renders errors when data is invalid", %{conn: conn} do
conn = post conn, admin_path(conn, :create), admin: @invalid_attrs
assert json_response(conn, 422)["errors"] != %{}
end
end
admin_controller.ex
defmodule MyApp.AdminController do
use MyApp.Web, :controller
alias MyApp.Admin
plug :scrub_params, "admin" when action in [:create]
def create(conn, %{"admin" => admin_params}) do
changeset = Admin.registration_changeset(%Admin{}, admin_params)
case Repo.insert(changeset) do
{:ok, admin} ->
conn
|> put_status(:created)
|> render("show.json", admin: admin)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(MyApp.ChangesetView, "error.json", changeset: changeset)
end
end
end
最后是我的router.ex部分
defmodule MyApp.Router do
# [...]
pipeline :api do
plug :accepts, ["json"]
end
scope "/api/v1", MyApp do
pipe_through :api
resources "/admins", AdminController, only: [:create]
end
# [...]
end
非常感谢任何帮助!感谢
答案 0 :(得分:3)
错误来自:
setup %{conn: conn} do
将其更改为:
setup do