如何使用RSpec测试ActionCable通道?

Dan*_*ani 14 rspec ruby-on-rails ruby-on-rails-5 actioncable

我想知道测试ActionCable频道.

假设我有以下聊天频道:

class ChatChannel < ApplicationCable::Channel
  def subscribed
    current_user.increment!(:num_of_chats)

    stream_from "chat_#{params[:chat_id]}"
    stream_from "chat_stats_#{params[:chat_id]}"
  end
end
Run Code Online (Sandbox Code Playgroud)

subscribed方法更新数据库并定义了两个要在整个频道上广播的流,但细节不是很重要,因为我的问题更为通用:

  • 如何通过订阅此频道来设置测试以测试所涉及的逻辑?

RSpec在测试类似的交互操作(如控制器操作)时提供了许多辅助方法和各种实用程序,但我可以找到有关RSpec和ActionCable的任何内容.

Leo*_*lán 8

您可能希望等待*for https://github.com/rails/rails/pull/23211合并.它添加了ActionCable :: TestCase.一旦合并,期望rspec-rails团队尽其所能:https://github.com/rspec/rspec-rails/issues/1606

*等待是可选的; 您不能等待并根据自己的工作进行"正在进行的工作",并找到一个现在可行的解决方案.


zhi*_*sme 5

你可以使用`action-cable-testing` gem。

将此添加到您的 Gemfile
gem 'action-cable-testing'
然后运行
$ bundle install

然后添加以下规范

# spec/channels/chat_channel_spec.rb

require "rails_helper"

RSpec.describe ChatChannel, type: :channel do
  before do
    # initialize connection with identifiers
    stub_connection current_user: current_user
  end

  it "rejects when no room id" do
    subscribe
    expect(subscription).to be_rejected
  end

  it "subscribes to a stream when room id is provided" do
    subscribe(chat_id: 42)

    expect(subscription).to be_confirmed
    expect(streams).to include("chat_42")
    expect(streams).to include("chat_stats_42")
  end
end
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅 github 存储库中的自述文件。

https://github.com/palkan/action-cable-testing

rspec 和 test_case 都有例子