skip to content

In Rails, how do you test an Action Cable connection and a channel with ActionCable::Connection::TestCase and ActionCable::Channel::TestCase?

level: seniorimportance: should knowfreq 30%

answer

  1. no socket, no server
  2. cookies.signed then connect
  3. assert_reject_connection
  4. stub_connection, then subscribe
  5. assert_has_stream_for, assert_broadcast_on

basics

~10 s

Connection tests set cookies, call connect and assert on connection.current_user, or wrap connect in assert_reject_connection. Channel tests call stub_connection(current_user:), subscribe(ticket_id:), then check subscription.confirmed? or rejected?, assert_has_stream_for, and perform with assert_broadcast_on.

solid answer

~30 s

Both test cases run in-process with no WebSocket. In `ActionCable::Connection::TestCase` you set `cookies.signed[:user_id]` (a test jar, no real signing), call `connect` (optionally with `params:`, `headers:`, `session:` or `env:`), and assert `connection.current_user`; `assert_reject_connection { connect }` passes when `connect` raises `UnauthorizedError`. In `ActionCable::Channel::TestCase`, `stub_connection(current_user: users(:customer))` builds a stub whose identifier methods return those values without running `connect`; `subscribe(ticket_id: 42)` runs `subscribed`, after which you check `subscription.confirmed?`, `subscription.rejected?`, `assert_has_stream_for ticket` or `assert_no_streams`. `perform :speak, body: "Hi"` calls an action; `transmissions` lists direct transmits, and `assert_broadcast_on(ticket, ...)` checks broadcasts through the test adapter that `ActionCable::TestHelper` installs.

code

ruby · 13 lines
ruby
require "test_helper"

class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
  test "connects with a signed user cookie" do
    cookies.signed[:user_id] = users(:agent).id
    connect
    assert_equal users(:agent), connection.current_user
  end

  test "rejects a missing cookie" do
    assert_reject_connection { connect }
  end
end

go deeper

for a junior

Recall that Rails has a connection test case and a channel test case, and that subscribe and perform drive a channel in a test.

for a middle

Explain stub_connection, the confirmed?/rejected? checks, assert_has_stream_for, and how cookies.signed works in a connection test.

for a senior

Show a test plan that pins authorisation: rejected foreign tickets, broadcasts asserted with the test adapter, and cleanup paths that run for rejected subscriptions.

for a principal

Decide the split between fast channel unit tests and slower browser tests for real-time features, and what must be covered before a channel ships.

## What Rails gives you Rails ships three test classes for Action Cable, all subclasses of `ActiveSupport::TestCase`, so they run under Minitest with fixtures like any other test: | Class | Tests | Key helpers | |---|---|---| | `ActionCable::Connection::TestCase` | `ApplicationCable::Connection` | `connect`, `disconnect`, `cookies`, `assert_reject_connection` | | `ActionCable::Channel::TestCase` | one channel class | `stub_connection`, `subscribe`, `perform`, `transmissions`, stream assertions | | `ActionCable::TestCase` | broadcasts from any code | `assert_broadcasts`, `assert_no_broadcasts`, `assert_broadcast_on`, `capture_broadcasts` | None of them opens a socket or boots a server. `bin/rails generate channel TicketChat` also writes `test/channels/ticket_chat_channel_test.rb` with a commented example. RSpec users get channel specs from rspec-rails instead. ## Connection tests The connection under test is inferred from the test class name (`ApplicationCable::ConnectionTest`) or set with `tests ApplicationCable::Connection`. - `cookies` is a test cookie jar. `cookies.signed[...]` and `cookies.encrypted[...]` store plain values, so you exercise the same reader your `connect` uses without real signing or encryption. - `connect(path = mount_path, params:, headers:, session:, env:)` builds a test request, instantiates the connection and calls its `connect`. - `connection` then exposes the identifiers, such as `connection.current_user`. - `assert_reject_connection { connect }` is `assert_raises(ActionCable::Connection::Authorization::UnauthorizedError)`. - `disconnect` calls the connection's `disconnect` method for cleanup logic. ## Channel tests The channel is inferred from the class name (`TicketChatChannelTest`) or set with `tests TicketChatChannel`. 1. `stub_connection(current_user: users(:customer))` builds a `ConnectionStub` that defines one method per identifier returning the given value. The real `connect` is not run, which keeps channel tests about the channel. 2. `subscribe(ticket_id: 42)` instantiates the channel with those params and runs `subscribe_to_channel`, so `subscribed` and its callbacks run. 3. Assert the outcome: `subscription.confirmed?`, `subscription.rejected?`, `assert_has_stream "desk_announcements"`, `assert_has_stream_for ticket`, `assert_has_no_stream_for other_ticket`, or `assert_no_streams`. 4. `perform :speak, body: "Hi"` calls the action with string-keyed data plus `"action"`, as a real client would. It raises "Must be subscribed!" if there is no subscription or it was rejected. 5. `transmissions` returns the messages the channel sent with `transmit`; `unsubscribe` runs `unsubscribed`. In the test, `stream_from` is replaced so it only records the broadcasting name; no adapter subscription is made. That is why `assert_has_stream_for` works without a running server, and why it must be given the record rather than a hand-built string: it computes the name with the channel's `broadcasting_for`. ## Broadcast assertions `ActionCable::TestHelper`, included in all three classes, replaces `ActionCable.server.pubsub` with `ActionCable::SubscriptionAdapter::Test` in `before_setup` and restores it afterwards, whatever `config/cable.yml` says. The test adapter records every broadcast per name: - `assert_broadcasts("desk_announcements", 1) { ... }` counts messages; - `assert_broadcast_on(name, data) { ... }` passes if a message equal to `data` (compared after a JSON round trip) was sent; - `capture_broadcasts(name) { ... }` returns the decoded messages for custom checks. Inside a channel test, `assert_broadcasts` and `assert_broadcast_on` also accept a record and turn it into the channel's broadcasting name. ## What to cover for a ticket chat - the connection accepts a valid signed cookie and rejects a missing or unknown one; - `subscribed` streams the user's own ticket and rejects someone else's; - `speak` broadcasts the expected payload, and refuses on a closed ticket; - `unsubscribed` cleanup works even for a rejected subscription. End-to-end behaviour in a real browser belongs in system tests; these unit tests keep the authorisation rules fast and exact. ## Mistakes that make these tests lie - **Asserting a hand-built stream name.** `assert_has_stream "ticket_chat_42"` fails when the channel calls `stream_for`, because the real name is `ticket_chat:` plus the GlobalID; use `assert_has_stream_for` with the record so the test computes the name the way the channel does. - **Testing only the happy path.** The rejected subscription is the security property; assert `subscription.rejected?` and `assert_no_streams` for a foreign ticket. - **Comparing broadcasts with symbol keys in mind.** `assert_broadcast_on` JSON round-trips the expected hash, so symbol and string keys compare equal, but values such as times are compared in their JSON form. - **Calling `perform` after a rejection.** It raises "Must be subscribed!", which is a test bug, not a channel bug. - **Stubbing more identifiers than the connection declares.** `stub_connection` accepts any keys, so a typo like `user:` instead of `current_user:` leaves the channel calling a method that does not exist.

  • Why do assert_broadcast_on checks pass even when config/cable.yml names another adapter for the test environment?
    `ActionCable::TestHelper#before_setup` swaps `ActionCable.server.pubsub` for an `ActionCable::SubscriptionAdapter::Test` instance and restores the original in `after_teardown`. The test adapter records each broadcast per name, which is what the broadcast assertions read, so they do not depend on the configured adapter.
  • Why test the channel with stub_connection rather than through connect?
    `stub_connection` sets the identifiers directly, so a channel test checks only the channel's own rules: streams, rejection, actions. Authentication is tested once in the connection test. Mixing them makes every channel test depend on cookie setup and hides which layer failed.

  • Channel tests need a running Puma server and a real WebSocket client.
  • assert_has_stream "ticket_42" verifies a stream_for ticket subscription.
  • assert_broadcast_on only works if cable.yml sets the redis adapter for the test environment.
  • stub_connection runs the real ApplicationCable::Connection#connect with those values.
  • perform can exercise an action on a rejected subscription.