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
还将自动提供以下实例方法供测试使用
- 连接
-
一个
ActionCable::Channel::ConnectionStub
,代表当前的 HTTP 连接。 - 订阅
-
当前通道的实例,在您调用
subscribe
时创建。 - 传输
-
已传输到通道的所有消息的列表。
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
命名空间
包含的模块