Test WebSockets

This guide shows you how to write tests for WebSocket channels.

Mock WebSocket

Create a mock WebSocket for testing:

# spec/support/mock_websocket.cr
class MockWebSocket
  getter sent_messages = [] of String
  getter closed = false
  getter close_code : Int32?
  getter close_reason : String?

  def send(message : String)
    @sent_messages << message
  end

  def close(code : Int32? = nil, reason : String? = nil)
    @closed = true
    @close_code = code
    @close_reason = reason
  end

  def object_id
    0_u64
  end
end

Testing Channel Connection

Testing Message Handling

Testing Disconnection

Testing Broadcasting

Testing Room-Based Channels

Testing Authentication

Integration Testing

Test WebSocket with real connections:

See Also

Last updated

Was this helpful?