How can I test ActionCable channels using RSpec?

I am wondering about testing ActionCable channels.

Let's say I have the following chat channel:

class ChatChannel < ApplicationCable::Channel
  def subscribed

    stream_from "chat_#{params[:chat_id]}"
    stream_from "chat_stats_#{params[:chat_id]}"

The subscribed method updates the db and defines two streams to be broadcasted across the channel, but the details are not very important since my question is a more general one:

  • How can I set up a test to test the logic involved by subscribing to this channel?

RSpec provides a lot of helper methods and various utilities when testing similar interactions like controller action, but I could find anything regarding RSpec and ActionCable.


You probably want to wait* for to be merged. It adds ActionCable::TestCase. Once that's merged, expect the rspec-rails team to do its part:

* 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.

I would install and configure TCR gem for recording sockets interaction ('its like VCR for websockets')

A spec for this in your case might look something like this...

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|
        # ...
        expect(cassette).to include "something ..."

You can use `action-cable-testing` gem.

Add this to your Gemfile gem 'action-cable-testing' Then run $ bundle install

Then add following spec

# 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

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

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

For more information see readme in github repo.

There are examples for both rspec and test_case

Need Your Help

PHP error: undefined symbol: _estrndup

php c apache makefile configure

I compile Apache-MySQL-PHP by hand to build a custom install using the configure options from below. When I start apache it fails to start and adds the below error in the error_log.

PHP removing items in multidimensional array

php arrays multidimensional-array

Got this array returned from Google Analytics Reporting API.