(RuntimeError) 期望连接有响应

(RuntimeError) expected connection to have a response

我是 Phoenix Framework 的新用户,我正在尝试设置一个简单的 HTTP POST 服务,该服务对传入数据执行计算并 returns 结果,但我'我收到以下错误:

** (RuntimeError) expected connection to have a response but no response was set/sent
 stacktrace:
   (phoenix) lib/phoenix/conn_test.ex:311: Phoenix.ConnTest.response/2
   (phoenix) lib/phoenix/conn_test.ex:366: Phoenix.ConnTest.json_response/2
   test/controllers/translation_controller_test.exs:20

我的测试用例:

test "simple POST" do
  post conn(), "/api/v1/foo", %{"request" => "bar"}
  IO.inspect body = json_response(conn, 200)
end

我的路由器定义:

scope "/api", MyWeb do
  pipe_through :api

  post "/v1/foo", TranslationController, :transform
end

我的控制器:

def transform(conn, params) do
  doc = Map.get(params, "request")
  json conn, %{"response" => "grill"}
end

我错过了什么?

在您的测试中,您使用 Plug.Test.conn/4 获取 Plug.Conn 结构并将其作为参数传递给 post。但是,您不会将结果存储在名为 conn.

的变量中

这意味着在检查 json_response 时第二次使用 conn 实际上是对 Plug.Test.conn/4.

的第二次调用

试试这个:

test "simple POST" do
  conn = post conn(), "/api/v1/foo", %{"request" => "bar"}
  assert json_response(conn, 200) == <whatever the expected JSON should be>