This gem provides missing testing utils for Action Cable.
NOTE: this gem is just a combination of two PRs to Rails itself (#23211 and #27191) and (hopefully) will be merged into Rails eventually.
NOTE 2: this is the documentation for (mostly) RSpec part of the gem. For Minitest usage see the repo's Readme or Minitest Usage chapter.
Add this line to your application's Gemfile:
group :test, :development do
gem 'action-cable-testing'
end
And then execute:
$ bundle
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"
To use have_broadcasted_to
/ broadcast_to
matchers anywhere in your specs, set your adapter to test
in cable.yml
:
# config/cable.yml
test:
adapter: test
And then use these matchers, for example:
RSpec.describe CommentsController do
describe "POST #create" do
expect { post :create, comment: { text: 'Cool!' } }.to
have_broadcasted_to("comments").with(text: 'Cool!')
end
end
You can also unit-test your channels:
# spec/channels/chat_channel_spec.rb
require "rails_helper"
RSpec.describe ChatChannel, type: :channel do
before do
# initialize connection with identifiers
stub_connection user_id: user.id
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(room_id: 42)
expect(subscription).to be_confirmed
expect(streams).to include("chat_42")
end
end
Bug reports and pull requests are welcome on GitHub at https://github.com/palkan/action-cable-testing.