15

我想知道如何测试 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 的任何信息。

4

4 回答 4

8

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

* 等待是可选的;您不能等待,并将自己的工作基于此“进行中的工作”,并找到立即有效的解决方案。

于 2016-11-08T03:50:17.327 回答
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

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

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

rspec 和 test_case 都有示例

于 2018-01-31T13:49:16.480 回答
3

我会安装和配置TCR gem来记录套接字交互('它就像 websockets 的 VCR')

在您的情况下,此规范可能看起来像这样......

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
于 2016-02-05T16:56:45.873 回答
2

现在 Rails 6 包含了action-cable-test gem

所以没有必要添加宝石。你可以做

assert_has_stream "chat_1"

或者,使用 rspec:

expect(subscription).to have_stream_from("chat_1") 
于 2020-12-11T14:35:15.380 回答