0

如何在通道測試中自動將ecto結構體序列化爲json響應?正如我在documentationThe event’s message must be a serializable map中看到的,我在answertutorial中發現,當我在模型中使用Poison.Encoder時,任何通過傳輸(據我所知)傳遞的消息都應該被編碼。如何在Phoenix.Secket.Broadcast載荷中測試或序列化結構?

實施例模型:從信道的功能之一

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} 

然後它上升不匹配在有效負載中沒有序列化結構的錯誤(我試圖匹配只有派生模型filelds):

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消息,如果它是客戶端應用程序?

+0

爲什麼你希望客戶端接收'Phoenix.Socket.Broadcast'?當我們做擴音器「Hello world」時,我們的伴侶會聽到單個「Hello world」消息,而不是被擴音器本身猛擊:) – mudasobwa

回答

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 
+0

但是爲什麼我無法獲得已編碼的有效載荷?我想知道Phoenix在哪裏編碼,我可以在哪裏攔截完整的響應? – luzny

+0

我想[this](https://github.com/phoenixframework/phoenix/blob/074a584ae324f78fa89f7ca097c38f8805d3021e/lib/phoenix/transports/websocket.ex#L190-L192)行處理JSON編碼。在Elixir消息發送到測試過程之後,據我所知,這種情況發生得非常晚。 – Dogbert