How can I test ActionCable using RSpec?

2019-08-26 09:19发布

This is my NotificationChannel

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

  def unsubscribed
    stop_all_streams
  end
end
  • How can I write test for this ActionCable channels

This is my 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

when I run this spec it gives error

Wrong number of arguments. Expected 2, got 1

I used this link to write code for stub and this file.

Rails version - 5.0.0.1 Ruby version - 2.3.1

1条回答
混吃等死
2楼-- · 2019-08-26 10:01
expect(@action_cable).to receive(:broadcast).with("notification_user_#{@user.id}")

Looking closely broadcast needs two parameters so

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

I cant guess what is going on however one issue is

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

You need an action for perform_action. However you dont have any action defined in NotificationsChannel.

Otherwise you can try

NotificationChannel.broadcast_to("notification_user_#{@user.id}", data )
查看更多
登录 后发表回答