ActionCable 通道的 RSpec 测试中未定义方法“stub_connection”

Kev*_*ica 2 ruby rspec ruby-on-rails-5 actioncable

我有以下测试:

require "rails_helper"

RSpec.describe MyChannel, type: :channel do
  let (:current_user) { User.first }

  it "subscribes to a unique room for the user" do
    stub_connection current_user: User.first
    subscribe
    expect(subscription).to be_confirmed
    expect(streams).to include("my_channel_#{current_user.id}")
  end
end
Run Code Online (Sandbox Code Playgroud)

它因以下错误而失败:

 Failure/Error: stub_connection current_user: User.first

 NoMethodError:
   undefined method `stub_connection' for #<RSpec::ExampleGroups::MyChannel:0x00000000deadbeef>
 # ./spec/channels/my_channel_spec.rb:7:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

根据文档和我找到的所有示例,stub_connection应该可以在 RSpec 通道测试中自动使用。我究竟做错了什么?

Kev*_*ica 5

我需要安装action-cable-testing gem。当我写这个答案时,这个 gem 的功能预计会在 Rails 6 的某个时刻直接集成到 Rails 中

安装 gem后,请确保在您的文件中需要 gemrails_helper.rb

RSpec 用法

首先,您需要安装 rspec-rails。

其次,将其添加到您的"rails_helper.rb"要求之后environment.rb

require "action_cable/testing/rspec"