我知道我可以测试 Action Cable 消息是否像这样广播:
expect {
ActionCable.server.broadcast "messages", text: 'Hi!'
}.to have_broadcasted_to("messages").with(text: 'Hi!')
我正在测试一个模块,作为其所需的副作用之一,应该广播多条消息。我希望能够断言这些消息包含某些信息。这样做的最佳习惯用法是什么?
我想编写一个测试来执行此操作,但我确信这不是惯用的:
result = expect { function_i_am_testing() }
result.to have_broadcasted_to("channel").with("Expected message 1")
result.to have_broadcasted_to("channel").with("Expected message 2")
result.to have_broadcasted_to("channel").with("Expected message 3")
看起来
ActionCable::TestHelper.capture_broadcasts
可能会满足您的需要。您可能需要在测试课程的顶部include ActionCable::TestHelper
。
messages = capture_broadcasts("channel") do
function_i_am_testing()
end
assert_equal({ text: 'Expected message 1' }, messages[0])
assert_equal({ text: 'Expected message 2' }, messages[1])
assert_equal({ text: 'Expected message 3' }, messages[2])