如何在通道测试用例中读取新的 Phoenix 通道实例的状态?

How to read new Phoenix channel instance's state in Channel test case?

我有以下处理传入消息的 phoenix 通道,广播它然后更新通道实例的 socket 状态:

defmodule MyApp.MyChannel do
  use MyApp.Web, :channel

  def join("topic", _payload, socket) do
    {:ok, socket}
  end

  def handle_in("update", %{"new_number" => number_}, socket) do
    broadcast socket, "update", %{"new_number" => number_} 
    {:noreply, assign(socket, :current_number, number_)}
  end
  ...
end

我正在尝试通过此测试用例测试 handle_in("update", ...) 函数的行为:

test "should broadcast new number and update the relevant instance's socket state", %{socket: socket} do
  push socket, "update", %{"new_number" => 356}
  assert_broadcast "update", %{"new_number" => 356}
  ## This is testing against the old state
  ## which is going to obviously fail
  assert socket.assigns[:current_number] == 356  
end

这里的问题是我找不到在测试用例中获取新的更新 socket 状态的方法。

测试用例中推送消息后,如何获取更新的socket

socket状态包含一个channel_pid条目,基本上包含频道的pid

前面结合:sys.get_state/1函数,取一个GenServer的pid和returns最近的state是关键!

示例,给定测试用例中的 socket 状态:

:sys.get_state(socket.channel_pid).assigns[:current_number]

感谢 Dogbert 对问题的评论。