Nona
Nona

Reputation: 5462

How to set the body of a PUT request in Elixir/phoenix with Plug.Adapters.Test.Con

So I have test setup as follows using Elixir/Phoenix and ESpec testing framework:

let :response do
  resp = build_conn() |> put("/kites/#{id_function()}", [horizontal: "more", default: true])
  Poison.Parser.parse!(resp.resp_body, keys: :atoms!)
end

When I call response(), I get an error such as:

** (Poison.EncodeError) unable to encode value: {Plug.Adapters.Test.Conn, %{chunks: nil, method: "PUT", owner: #PID<0.46.0>, params: nil, ref: #Reference<0.0.5.1528>, req_body: ""}}
      (poison) lib/poison/encoder.ex:354: Poison.Encoder.Any.encode/2
      (poison) lib/poison/encoder.ex:213: anonymous fn/4 in Poison.Encoder.Map.encode/3
      (poison) lib/poison/encoder.ex:214: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
      (poison) lib/poison/encoder.ex:214: Poison.Encoder.Map.encode/3
      (poison) lib/poison/encoder.ex:213: anonymous fn/4 in Poison.Encoder.Map.encode/3
      (poison) lib/poison/encoder.ex:214: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
      (poison) lib/poison/encoder.ex:214: Poison.Encoder.Map.encode/3
      (poison) lib/poison/encoder.ex:213: anonymous fn/4 in Poison.Encoder.Map.encode/3


1 examples, 1 failures

Finished in 1.0 seconds (0.76s on load, 0.24s on specs)

What is going on? Am I passing the parameters to PUT request correctly?

Upvotes: 1

Views: 830

Answers (1)

Karol Gasienica
Karol Gasienica

Reputation: 2904

It looks for me like you want to encode map while you got a tuple.

You have:

{Plug.Adapters.Test.Conn, %{chunks: nil, method: "PUT", owner: #PID<0.46.0>, params: nil, ref: #Reference<0.0.5.1528>, req_body: ""}}

a tuple with {some_val, %{} where %{} is a map. You probably want to encode just a map, so it's second element. You can take second element from tuple by using: elem(resp.resp_body, 1)

Maybe it will work:

Poison.Parser.parse!(elem(resp.resp_body, 1), keys: :atoms!)

Or just create a map from it with:

Enum.into(resp.resp_body, %{})

I'm not sure if I'm pointing in right place, but it seems like resp.resp_body has more inside than you expect.


One more thing, remember that keys: :atoms! reuses existing atoms, i.e. if :some_var was not allocated before the call, you will encounter an argument error message.

So maybe just deleting it may help:

Poison.Parser.parse!(resp.resp_body)

Upvotes: 1

Related Questions