How do you set the body of a POST request in an Elixir Plug test?

Zub*_*bin 3 elixir

Using Plug.Test.conn, setting the request body doesn't seem to work.

Here's the plug:

defmodule MyPlug do
  import Plug.Conn

  def init(_), do: nil

  def call(conn, _) do
    {:ok, body, _conn} = read_body(conn)
    send_resp(conn, 200, "body: #{body}")
  end
end
Run Code Online (Sandbox Code Playgroud)

Using curl:

$ curl -X POST -d foo=bar http://localhost:4000/
body: foo=bar
Run Code Online (Sandbox Code Playgroud)

Using Plug.Test:

defmodule MyTest do
  use ExUnit.Case, async: false
  use Plug.Test

  test "POST request" do
    conn = conn(:post, "/", %{foo: "bar"})
           |> MyPlug.call(%{})
    assert conn.resp_body == "body: foo=bar"
  end
end
Run Code Online (Sandbox Code Playgroud)

Failure:

  1) test POST request (MyPlugTest)
     test/my_plug_test.exs:28
     Assertion with == failed
     code:  conn.resp_body() == "body: foo=bar"
     left:  "body: "
     right: "body: foo=bar"
Run Code Online (Sandbox Code Playgroud)

I've also tried passing a string and setting content-type header as per docs.

Mik*_*hot 5

用于Poison.encode!在传递给之前将主体转换为二进制文件conn

defmodule MyPlug do
  import Plug.Conn

  def init(_), do: nil

  def call(conn, _) do
    {:ok, body, _conn} = read_body(conn)
    send_resp(conn, 200, "body: #{body}")
  end
end

defmodule MyTest do
  use ExUnit.Case
  use Plug.Test

  test "POST request" do
    conn = conn(:post, "/", Poison.encode!(%{foo: "bar"}))
           |> MyPlug.call(%{})
    assert conn.resp_body == ~S(body: {"foo":"bar"})
  end
end
Run Code Online (Sandbox Code Playgroud)

但是Plug.Conn.read_body只能使用一次,之后它将丢弃数据。因此,您可能想Plug.Parsers在管道中更早地解析主体:

plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  json_decoder: Poison
Run Code Online (Sandbox Code Playgroud)

解析后,该主体可以按conn.body_params和合并使用conn.params