我可以在 ActiveJob 测试中测试
broadcasts_refreshes
吗?或者也许在我的模型测试中?我应该在其他地方测试这个吗?
Broadcastable
文档(我添加了重点):
配置模型进行广播 流名称的“页面刷新” 在运行时通过broadcasts_refreshes
符号调用 派生stream
ActionCable TestHelpers都要求您指定一个流,但没有提及如何找出派生流名称,因此 我检查了
Broadcastable
代码,看起来像 broadcasts_refreshes
当前使用 model_name.plural
来导出流名称。
assert_broadcasts(stream, number, &block)
和 model_name.plural
的字符串结果(在我的例子中为“salesforce_contacts”)并将该代码作为流名称传递,但在这两种情况下,我都收到测试失败并显示以下消息:
1 broadcasts to salesforce_contacts expected, but 0 were sent.
# Testing the background job
require "test_helper"
class UpdateSFContactJobTest < ActiveJob::TestCase
include ActionCable::TestHelper
test "broadcasts refresh message on change" do
contact = salesforce_contacts(:one)
assert_broadcasts(contact.model_name.plural, 1) do
UpdateSFContactJob.perform_now(contact)
end
#Assertion fails: 1 broadcasts to salesforce_contacts expected, but 0 were sent.
end
end
# Testing the model
require "test_helper"
class Salesforce::ContactTest < ActiveSupport::TestCase
include ActionCable::TestHelper
test "broadcasts refresh after change" do
contact = salesforce_contacts(:one)
assert_broadcasts(contact.model_name.plural, 1) do
contact.save
end
#Assertion fails: 1 broadcasts to salesforce_contacts expected, but 0 were sent.
end
end
我的模型代码的摘要版本是:
class Salesforce::Contact < ApplicationRecord
include Mappable
belongs_to :user
broadcasts_refreshes
permit_unexpected_attributes
has_attribute_mappings Id: :salesforce_id,
AccountId: :account_id,
npsp__Deceased__c: :deceased,
Name: :combined_name
#snip
end
turbo-rails
提供了assert_turbo_stream_broadcasts
助手:
class ModelTest < ActiveSupport::TestCase
test "the broadcast" do
model = Model.create!
model.broadcast_refresh
assert_turbo_stream_broadcasts model, count: 1
end
end
https://github.com/hotwired/turbo-rails#testing
它无法与
assert_broadcasts
一起使用的原因是您给它提供了错误的流名称:
>> model = Model.first
>> model.broadcast_refresh
[ActionCable] Broadcasting to Z2lkOi8vc3RhY2tvdmVyZmxvdy9BcnRpY2xlLzEzNA: "<turbo-stream action=\"refresh\"></turbo-stream>"
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# this is the expected stream name -'
# which is a global id in param form
>> model.to_gid_param
=> "Z2lkOi8vc3RhY2tvdmVyZmxvdy9BcnRpY2xlLzEzNA"
class ModelTest < ActiveSupport::TestCase
test "the broadcast" do
model = Model.create!
model.broadcast_refresh
assert_broadcasts model.to_gid_param, 1
end
end