如何使用 RSpec 测试 ActionCable?

How can I test ActionCable using RSpec?

这是我的 NotificationChannel

class NotificationChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notification_user_#{user.id}"
  end

  def unsubscribed
    stop_all_streams
  end
end

这是我的Rspec

require 'rails_helper'
require_relative 'stubs/test_connection'

RSpec.describe NotificationChannel, type: :channel do

  before do
    @user = create(:user)
    @connection = TestConnection.new(@user)
    @channel = NotificationChannel.new @connection, {}
    @action_cable = ActionCable.server
  end

  let(:data) do
    {
      "category" => "regular",
      "region" => "us"
    }
  end

  it 'notify user' do
#error is in below line
    expect(@action_cable).to receive(:broadcast).with("notification_user_#{@user.id}")
    @channel.perform_action(data)
  end
end

当我运行这个规范时它给出了错误

Wrong number of arguments. Expected 2, got 1

我用 this link 为存根和这个文件编写代码。

Rails 版本 - 5.0.0.1 Ruby 版本 - 2.3.1

expect(@action_cable).to receive(:broadcast).with("notification_user_#{@user.id}")

仔细看广播需要两个参数所以

expect(@action_cable).to receive(:broadcast).with("notification_user_#{@user.id}", data)

我猜不出发生了什么,但有一个问题是

  let(:data) do
    {
      "action" => 'action_name',
      "category" => "regular",
      "region" => "us"
    }
  end

您需要为 perform_action 采取行动。 但是,您没有在 NotificationsChannel 中定义任何操作。

否则你可以试试

NotificationChannel.broadcast_to("notification_user_#{@user.id}", data )