How can I test ActionCable using RSpec?

心已入冬 提交于 2020-02-06 07:34:11

问题


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:


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 )


来源:https://stackoverflow.com/questions/49293150/how-can-i-test-actioncable-using-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!