如何使用 RSpec 测试 ActionCable 频道?

How can I test ActionCable channels using RSpec?

我想知道如何测试 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

subscribed 方法更新了数据库并定义了两个要跨频道广播的流,但细节不是很重要,因为我的问题是一个更笼统的问题:

RSpec 在测试控制器操作等类似交互时提供了很多辅助方法和各种实用程序,但我找不到任何关于 RSpec 和 ActionCable 的信息。

我会安装和配置 TCR gem 以记录套接字交互 ('its like VCR for websockets')

在您的案例中,此规范可能看起来像这样...

describe ChatChannel do
  context ".subscribed" do
    it "updates db and defines opens 2 streams for one channel" do
      TCR.use_cassette("subscribed_action") do |cassette|
        # ...
        ChatChannel.subscribed
        expect(cassette).to include "something ..."
      end
    end
  end
end

您可能需要等待* https://github.com/rails/rails/pull/23211 to be merged. It adds ActionCable::TestCase. Once that's merged, expect the rspec-rails team to do its part: https://github.com/rspec/rspec-rails/issues/1606

* Waiting is optional; You can not wait and based your own work on this "work in progress" and find a solution that works right now.

您可以使用 `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

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

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

rspec 和 test_case 都有示例

现在 Rails 6 包括 action-cable-test gem

所以没必要加一个gem。你可以做任何一个

assert_has_stream "chat_1"

或者,rspec:

expect(subscription).to have_stream_from("chat_1") 

看起来它已合并到 Rails 6. 查看发行说明 Action cable testing and the pr AC testing PR