控制器测试中的Ecto.NoResultsError

时间:2018-01-25 19:57:47

标签: elixir phoenix-framework ecto

在我的凤凰控制器中,我使用:

...
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

1 个答案:

答案 0 :(得分:4)

默认情况下,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