1

如何在通道测试中自动将 ecto struct 序列化为 json 响应?正如我在文档 The event’s message must be a serializable map中看到的那样,我在答案教程中发现,当我Poison.Encoder在模型中使用时,应该对通过传输层(据我了解)传递的任何消息进行编码。

示例模型:

use PhoenixTrello.Web, :model
  # ...

  @derive {Poison.Encoder, only: [:id, :first_name, :last_name, :email]}

  # ...
end

从频道功能之一广播:

broadcast_from! socket, "card:created", %{card: card}

最后尝试在测试中从广播接收有效载荷:

assert_receive %Phoenix.Socket.Broadcast{topic: ^t1, event: "card:created", payload: ^payload}

然后它上升不匹配错误与有效载荷中未序列化的结构(我试图仅匹配派生模型文件):

Process mailbox:
  %Phoenix.Socket.Broadcast{event: "card:created", payload: %{card: %PhoenixTrello.Card{__meta__: #Ecto.Schema.Metadata<:loaded, "cards">, ... user: #Ecto.Association.NotLoaded<association :user is not loaded>, user_id: 1833}}, topic: "boards:1833"}

如何在测试中获取序列化的 json 消息,就好像它是客户端应用程序一样?

4

1 回答 1

0

我首先assert_receive是原始消息,然后Poison.encode!再做第二个assert

payload = "{\"card\": ...}"
assert_receive %Phoenix.Socket.Broadcast{topic: ^t1, event: "card:created", payload: raw_payload}
assert Poison.encode!(raw_payload) == payload
于 2017-03-02T09:51:46.633 回答