【问题标题】:How can I test ActionCable using RSpec?如何使用 RSpec 测试 ActionCable?
【发布时间】:2018-08-23 21:24:33
【问题描述】:

这是我的通知频道

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

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

Wrong number of arguments. Expected 2, got 1

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

Rails 版本 - 5.0.0.1 Ruby 版本 - 2.3.1

【问题讨论】:

  • 哪一行有错误?
  • 错误在expect(@action_cable) 行。我用评论更新了我的问题

标签: ruby-on-rails rspec ruby-on-rails-5 actioncable


【解决方案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 )

【讨论】:

  • NotificationChannel.broadcast_to("notification_user_#{@user.id}", data ) 相当于 expect(@action_cable).to receive(:broadcast).with("notification_user_#{@user.id}") @channel.perform_action(data) 或者我们只能在我们定义了一个动作时使用它,但在我的情况下只有 subscribedunsubscribed 以及 unsubscribed
  • 我更新了关于该错误的答案。 Perform_action 意味着当您从 javascript 执行以调用通道上的操作时(由框架自动调用)。 broadcast_to 是向订阅者广播消息,例如:“notification_user_#{user.id}”
猜你喜欢
  • 2018-11-06
  • 2016-05-15
  • 2018-07-07
  • 2019-04-11
  • 2018-07-30
  • 2013-12-07
  • 2019-12-10
  • 2013-06-16
  • 1970-01-01
相关资源
最近更新 更多