全书目录

第三十八篇:Phoenix 完全指南 —— 实时频道城邦宇宙

第二十章:Phoenix 的测试体系,也很有“城邦味”

1 分钟 164 字 第 739 / 962 个阅读单元

Phoenix 的好处之一,是不同治理层有各自清楚的测试入口。

#1. Controller / HTTP:ConnTest
elixir
test "GET /dispatches", %{conn: conn} do
  conn = get(conn, ~p"/dispatches")
  assert html_response(conn, 200) =~ "今日调度公报"
end
#2. LiveView:Phoenix.LiveViewTest
elixir
test "can create dispatch", %{conn: conn} do
  {:ok, view, _html} = live(conn, ~p"/live/dispatches")

  html =
    view
    |> form("form", dispatch: %{title: "东门警报"})
    |> render_submit()

  assert html =~ "东门警报"
end
#3. Channel:Phoenix.ChannelTest
elixir
test "report_incident broadcasts to district" do
  {:ok, _, socket} =
    socket(CityWeb.UserSocket, "user:1", %{current_user: %{id: 1}})
    |> subscribe_and_join(CityWeb.DistrictChannel, "district:42")

  ref = push(socket, "report_incident", %{"title" => "南门拥堵"})
  assert_reply ref, :ok, %{id: _id}
  assert_broadcast "incident_reported", %{title: "南门拥堵"}
end

这种分层测试体验非常 Phoenix:

text
窗口怎么回:测 HTTP
中控室怎么反应:测 LiveView
频道塔怎么广播:测 Channel

不是所有东西都塞进 E2E 黑箱里。