Search code examples
rubyrspecruby-on-rails-5actioncable

Undefined method `stub_connection' in RSpec test for ActionCable channel


I have the following test:

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

It fails with this error:

 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)>'

According to the documentation and all of the examples I've found, stub_connection should be available automagically in an RSpec channel test. What am I doing wrong?


Solution

  • I needed to install the action-cable-testing gem. As of when I'm writing this answer, this gem's functionality is slated to be integrated directly into Rails at some point in Rails 6.

    After installing the gem, make sure to require the gem in your rails_helper.rb file:

    RSpec Usage

    First, you need to have rspec-rails installed.

    Second, add this to your "rails_helper.rb" after requiring environment.rb:

    require "action_cable/testing/rspec"