如何使用RSpec通过用户通道测试ActiveJob广播消息?

时间:2019-06-26 08:09:20

标签: rspec-rails actioncable

我正在遵循RSpec指南,了解如何测试是否已使用ActionCable广播消息。

这是他们的例子:

RSpec.describe CommentsController do
  describe "POST #create" do
    expect { post :create, comment: { text: 'Cool!' } }.to
      have_broadcasted_to("comments").with(text: 'Cool!')
  end
end

这是我的ActiveJob:

  def perform(document_id, proofreading_job_id, current_user_id)
    document.paragraph_details.destroy_all
    broadcast_message message: "Determining the exact amount of time to proofread your document"
    document.create_paragraph_details
    broadcast_message message: "Determining the earliest delivery date..."
    proofreading_job.set_duration
    broadcast_message message: "Scheduling your proofreading job..."
    proofreading_job.schedule
    broadcast_message message: "Redirecting to your quotation", path: proofreading_job_quotation_path(proofreading_job)
  end

  def broadcast_message(message:, head: 302, path: nil)
    ActionCable.server.broadcast "notification_channel_user_#{current_user_id}", head: head, path: path, content: message
  end

这是我的Rspec测试:

RSpec.describe QuotationJob, type: :job do
  include ActiveJob::TestHelper

  let(:document)         { create(:document) }
  let(:current_user_id)  { document.proofreading_job.client_user.id }
  let(:proofreading_job) { document.proofreading_job }
  let!(:proofreader)     { create(:proofreader_with_work_events) }

  before do
    create(:job_rate, :proofreading)
  end

      it 'broadcasts messages to the current user while performing the job' do
        expect { QuotationJob.perform_now(document.id, proofreading_job.id, current_user_id) }
        .to have_broadcasted_to("notification_channel_user_#{current_user_id}").with(content: "Determining the exact amount of time to proofread your document")
      end

end

这是测试的输出:

  1) QuotationJob broadcasts messages to the current user while performing the job
     Failure/Error:
       expect { QuotationJob.perform_now(document.id, proofreading_job.id, current_user_id) }
       .to have_broadcasted_to("notification_channel_user_#{current_user_id}").with(content: "Determining the exact amount of time to proofread your document")

       expected to broadcast exactly 1 messages to notification_channel_user_23383 with {"content"=>"Determining the exact amount of time to proofread your document"}, but broadcast 0
       Broadcasted messages to notification_channel_user_23383:
         {"head":302,"path":null,"content":"Determining the exact amount of time to proofread your document"}
         {"head":302,"path":null,"content":"Determining the earliest delivery date..."}
         {"head":302,"path":null,"content":"Scheduling your proofreading job..."}
         {"head":302,"path":"/proofreading_jobs/6941/quotation","content":"Redirecting to your quotation"}

我知道这可以在开发中使用,因为我可以在屏幕上看到消息。但是,当我运行测试时,首先似乎没有消息发送。但是RSpec告诉我,实际上我正在测试的消息已经发送了。那么我该如何设计此测试才能使其正常工作?

0 个答案:

没有答案