为什么这个测试不能通过?

问题描述 投票:0回答:1

我做了一个测试来更新用户的变化集,应该通过无效的数据,但用户的验证不允许它通过,对不起,如果这是noob,IM刚开始在elixir

   test "renders errors when data is invalid", %{conn: conn, user: user} do
      assert conn = put(conn, Routes.api_user_path(conn, :update, user), user: @invalid_attrs)
      assert json_response(conn, 422)["errors"] != %{}
    end
  end

输出


** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid.

     Errors

         %{
           email: [{"can't be blank", [validation: :required]}],
           name: [{"can't be blank", [validation: :required]}],
           password: [{"can't be blank", [validation: :required]}],
           password__confirmation: [{"can't be blank", [validation: :required]}]
         }

     Applied changes

         %{is_active: nil}

     Params

         %{
           "email" => nil,
           "is_active" => nil,
           "name" => nil,
           "password" => nil,
           "password__confirmation" => nil
         }

     Changeset
Thats all lines been used

         #Ecto.Changeset<
           action: :update,
           changes: %{is_active: nil},
           errors: [
             name: {"can't be blank", [validation: :required]},
             email: {"can't be blank", [validation: :required]},
             password: {"can't be blank", [validation: :required]},
             password__confirmation: {"can't be blank", [validation: :required]}
           ],
           data: #TrelloClone.Auth.User<>,
           valid?: false
   @invalid_attrs %{name: nil, email: nil, is_active: nil,password: nil,password__confirmation: nil}


def update(conn, %{"id" => id, "user" => user_params}) do
    user = Auth.get_user!(id)

    with {:ok, %User{} = user} <- Auth.update_user(user, user_params) do
      render(conn, "show.json", user: user)
    end
  end


  def update_user(%User{} = user, attrs) do
    user
    |> User.changeset(attrs)
    |> Repo.update!()
  end


 def get_user!(id), do: Repo.get!(User, id)

所有的行都被使用了,obs:它们在不同的文件中,Auth是User的上下文。

elixir phoenix-framework
1个回答
1
投票

根据文档的规定。Repo.update! 你用 update_user/2

同理 Repo.update/2 但返回的是结构体或 如果变化集无效,则引发.

异常是在无效的变化集上提出的,你的测试就会爆炸。如果你想确实 抚养 在输入错误的情况下,您可以用以下方法修改测试结果 ExUnit.Assertions.assert_raise/2

test "renders errors when data is invalid", %{conn: conn, user: user} do
  assert_raise  Ecto.InvalidChangesetError, fn ->
    put(conn, Routes.api_user_path(conn, :update, user), user: @invalid_attrs)
  end
end

但既然你想显示 422,你最好使用 Repo.update/2update_user/2

def update_user(%User{} = user, attrs) do
  user
  |> User.changeset(attrs)
  |> Repo.update() # not Repo.update!()
end
© www.soinside.com 2019 - 2024. All rights reserved.