跳至内容 跳至搜索

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
命名空间
包含的模块