Skip to content

Instantly share code, notes, and snippets.

@gamache
Last active April 10, 2023 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamache/5663a361625c03c6b8be to your computer and use it in GitHub Desktop.
Save gamache/5663a361625c03c6b8be to your computer and use it in GitHub Desktop.
Phoenix.ConnTest appears not to pass request body to controller
# router.ex
defmodule Myapp.Router do
use Myapp.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/", Myapp do
pipe_through :api
post "/", PageController, :post
end
end
# page_controller.ex
defmodule Myapp.PageController do
use Myapp.Web, :controller
def post(conn, params) do
{:ok, body, conn} = conn |> Plug.Conn.read_body
conn |> json(%{"received_body": body})
end
end
# page_controller_test.exs
defmodule Myapp.PageControllerTest do
use Myapp.ConnCase
@endpoint Myapp.Endpoint
test "POST /" do
body_obj = %{"ok" => true}
resp = conn
|> put_req_header("content-type", "application/json")
|> post("/", Poison.encode!(body_obj))
%{"received_body" => received_obj} = resp.resp_body |> Poison.decode!
assert(body_obj == received_obj) # this test fails because received_obj == ""
end
end
@biocode666
Copy link

Pro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment