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