跳至內容 跳至搜尋

Action Cable 通道功能測試的超類別。

基本範例

功能測試的寫法如下:1. 首先使用 subscribe 方法來模擬訂閱建立。2. 然後確認目前的狀態是否如預期。這個「狀態」可以是任何東西:傳送的訊息、訂閱串流等等。

例如

class ChatChannelTest < ActionCable::Channel::TestCase
  def test_subscribed_with_room_number
    # Simulate a subscription creation
    subscribe room_number: 1

    # Asserts that the subscription was successfully created
    assert subscription.confirmed?

    # Asserts that the channel subscribes connection to a stream
    assert_has_stream "chat_1"

    # Asserts that the channel subscribes connection to a specific
    # stream created for a model
    assert_has_stream_for Room.find(1)
  end

  def test_does_not_stream_with_incorrect_room_number
    subscribe room_number: -1

    # Asserts that not streams was started
    assert_no_streams
  end

  def test_does_not_subscribe_without_room_number
    subscribe

    # Asserts that the subscription was rejected
    assert subscription.rejected?
  end
end

也可以執行操作: def test_perform_speak subscribe room_number: 1

  perform :speak, message: "Hello, Rails!"

  assert_equal "Hello, Rails!", transmissions.last["text"]
end

特殊方法

ActionCable::Channel::TestCase 也會自動提供下列執行個體方法來用於測試

connection

一個 ActionCable::Channel::ConnectionStub,代表目前的 HTTP 連線。

subscription

目前頻道的執行個體,在呼叫 subscribe 時建立。

transmissions

所有已傳送至頻道的所有訊息的清單。

Channel 會自動推論

ActionCable::Channel::TestCase 會自動從測試類別名稱推論受測的頻道。如果無法從測試類別名稱推論頻道,則可以使用 tests 明確設定。

class SpecialEdgeCaseChannelTest < ActionCable::Channel::TestCase
  tests SpecialChannel
end

指定連線識別碼

您必須手動設定連線以提供識別碼值。只要使用

stub_connection(user: users(:john))

測試廣播

ActionCable::Channel::TestCase 擴充了 ActionCable::TestHelper 斷言(例如 assert_broadcasts),以處理廣播至模型

# in your channel
def speak(data)
  broadcast_to room, text: data["message"]
end

def test_speak
  subscribe room_id: rooms(:chat).id

  assert_broadcast_on(rooms(:chat), text: "Hello, Rails!") do
    perform :speak, message: "Hello, Rails!"
  end
end
命名空間
內含的模組