(RuntimeError)期望连接有响应

sto*_*oft 8 elixir phoenix-framework

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

** (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
Run Code Online (Sandbox Code Playgroud)

我的测试用例:

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

我的路由器定义:

scope "/api", MyWeb do
  pipe_through :api

  post "/v1/foo", TranslationController, :transform
end
Run Code Online (Sandbox Code Playgroud)

我的控制器:

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

我错过了什么?

小智 11

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

这意味着第二次使用时conn,检查时json_response实际上是第二次调用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>
Run Code Online (Sandbox Code Playgroud)