Skip to content

Commit 966e8f5

Browse files
committed
feat: backport command callbacks testing
1 parent 5d0ade5 commit 966e8f5

2 files changed

Lines changed: 49 additions & 2 deletions

File tree

lib/anycable/rails/action_cable_ext/connection.rb

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,43 @@ def around_command(*methods, &block)
4848
end)
4949

5050
ActionCable::Connection::Base.prepend(Module.new do
51-
def dispatch_websocket_message(*)
51+
def dispatch_websocket_message(websocket_message)
5252
return super unless websocket.alive?
5353

54-
run_callbacks(:command) { super }
54+
handle_channel_command(decode(websocket_message))
55+
end
56+
57+
def handle_channel_command(payload)
58+
run_callbacks :command do
59+
subscriptions.execute_command payload
60+
end
61+
end
62+
end)
63+
end
64+
65+
# Trigger autoload
66+
test_case_defined = false
67+
68+
begin
69+
ActionCable::Connection::TestCase # rubocop:disable Lint/Void
70+
test_case_defined = true
71+
rescue NameError
72+
end
73+
74+
# Backport: https://github.com/rails/rails/pull/45445
75+
if test_case_defined && !ActionCable::Connection::TestConnection.method_defined?(:transmissions)
76+
ActionCable::Connection::TestConnection.prepend(Module.new do
77+
attr_reader :transmissions
78+
79+
def initialize(*)
80+
super
81+
82+
@transmissions = []
83+
@subscriptions = ActionCable::Connection::Subscriptions.new(self)
84+
end
85+
86+
def transmit(cable_message)
87+
transmissions << cable_message.with_indifferent_access
5588
end
5689
end)
5790
end

spec/integrations/action_cable_testing_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,5 +65,19 @@ def connection_class
6565

6666
expect(ApplicationCable::Connection.events_log.last.fetch(:data)).to eq(name: "max", url: "http://test.host/cable?token=123")
6767
end
68+
69+
specify "callbacks" do
70+
connect "/cable?token=123", session: {username: user.name}
71+
72+
connection.handle_channel_command(
73+
{
74+
"identifier" => {channel: "ChatChannel"}.to_json,
75+
"command" => "subscribe"
76+
}
77+
)
78+
79+
expect(connection.transmissions.last["type"]).to eq("confirm_subscription")
80+
expect(ApplicationCable::Connection.events_log.last[:source]).to eq "command"
81+
end
6882
end
6983
end

0 commit comments

Comments
 (0)