id}) do post = Repo.get!(Post, id) -6ren">
gpt4 book ai didi

elixir - Controller 测试中的 Ecto.NoResultsError

转载 作者:行者123 更新时间:2023-12-04 00:32:52 24 4
gpt4 key购买 nike

在我的 Phoenix Controller 中,我使用:

...
def delete(conn, %{"id" => id}) do
post = Repo.get!(Post, id)
with {:ok, %{post: %Post{}}} <- Posts.delete_post(post) do
send_resp(conn, :no_content, "")
end
end
...

在我的测试中:

...
test "deletes chosen post", %{conn: orig_conn, user: user, post: post} do
conn = delete orig_conn, v1_post_path(orig_conn, :delete, post)
assert response(conn, 204)
conn = delete orig_conn, v1_post_path(orig_conn, :delete, post)
assert response(conn, 404)
end
...

但当帖子不存在时,此测试失败:

...
** (Ecto.NoResultsError) expected at least one result but got none in query:
...

为什么?如我所见this , Ecto.NoResultsError 应该返回 404 的状态

Phoenix 1.3 版,phoenix-ecto 3.3,ecto 2.1

最佳答案

默认情况下,Phoenix 会配置您的测试环境以呈现异常错误。这是故意的,否则代码中的错误将成为测试中的 500 页,并且您必须追溯它。这就是你得到异常的原因。

幸运的是,对于您想要检查此类异常会获得哪个状态代码的情况,有 assert_error_sent :

assert_error_sent :not_found, fn ->
get build_conn(), "/users/not-found"
end

assert_error_sent 404, fn ->
get build_conn(), "/users/not-found"
end

关于elixir - Controller 测试中的 Ecto.NoResultsError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com