如何使用 RSpec 测试 ActionCable? [英] How can I test ActionCable using RSpec?
本文介绍了如何使用 RSpec 测试 ActionCable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的通知频道
class NotificationChannel < ApplicationCable::Channel
def subscribed
stream_from "notification_user_#{user.id}"
end
def unsubscribed
stop_all_streams
end
end
- 如何为这个 ActionCable 频道编写测试
这是我的 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 版本 - 5.0.0.1Ruby 版本 - 2.3.1
Rails version - 5.0.0.1 Ruby version - 2.3.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
您需要为 perform_action 执行一个操作.但是,您没有在 NotificationsChannel 中定义任何操作.
You need an action for perform_action. However you dont have any action defined in NotificationsChannel.
否则你可以试试
NotificationChannel.broadcast_to("notification_user_#{@user.id}", data )
这篇关于如何使用 RSpec 测试 ActionCable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文