Class: LiveCable::Testing::TestChannel

Inherits:
Object
  • Object
show all
Defined in:
lib/live_cable/testing/test_channel.rb

Overview

Stand-in for an ActionCable channel. Records streams started via stream_from so tests can trigger their callbacks with receive_stream.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(identifiers = {}) ⇒ TestChannel

Returns a new instance of TestChannel.



14
15
16
17
# File 'lib/live_cable/testing/test_channel.rb', line 14

def initialize(identifiers = {})
  @streams = {}
  @connection = TestCableConnection.new(identifiers)
end

Instance Attribute Details

#connectionLiveCable::Testing::TestCableConnection (readonly)



12
13
14
# File 'lib/live_cable/testing/test_channel.rb', line 12

def connection
  @connection
end

#streamsHash<String, Hash> (readonly)

Returns Stream name => { coder:, callback: }.

Returns:

  • (Hash<String, Hash>)

    Stream name => { coder:, callback: }



9
10
11
# File 'lib/live_cable/testing/test_channel.rb', line 9

def streams
  @streams
end

Instance Method Details

#broadcast_to(name, payload) ⇒ Object

Simulate an external broadcast arriving on a stream. The payload goes through the stream's coder round trip, so a Hash payload arrives with string keys just like a production broadcast.

Parameters:

  • name (String)

    The stream name passed to stream_from

  • payload (Object)

    The broadcast payload

Raises:



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/live_cable/testing/test_channel.rb', line 33

def broadcast_to(name, payload)
  stream = @streams.fetch(name) do
    raise LiveCable::Error, "Component is not streaming from #{name.inspect} " \
                            "(active streams: #{@streams.keys.inspect})"
  end

  callback = stream[:callback]
  raise LiveCable::Error, "Stream #{name.inspect} has no callback" unless callback

  coder = stream[:coder]
  payload = coder.decode(coder.encode(payload)) if coder

  callback.call(payload)
end

#stop_stream_from(name) ⇒ Object



23
24
25
# File 'lib/live_cable/testing/test_channel.rb', line 23

def stop_stream_from(name)
  @streams.delete(name)
end

#stream_from(name, coder: nil, &block) ⇒ Object



19
20
21
# File 'lib/live_cable/testing/test_channel.rb', line 19

def stream_from(name, coder: nil, &block)
  @streams[name] = { coder:, callback: block }
end