如何为 ActionCable 通道写 Minitest 并发测试

解读

国内 Rails 项目普遍使用 Minitest 而非 RSpec,面试官想确认你能否在纯 Minitest 环境下验证 WebSocket 通道的并发安全与业务正确性。核心痛点是:ActionCable 的异步 I/O 与并发订阅会触发竞态条件,而官方只给出 RSpec 示例。你需要给出可落地的 Minitest 并发测试方案,包括:

  1. 如何启动嵌入式 Cable 服务器(避免单独开进程)
  2. 如何用并发原语(Thread、Queue、Mutex)模拟多客户端
  3. 如何断言消息顺序、去重、幂等等并发语义
  4. 如何稳定复现并发 bug(国内 CI 常因超时抖动而误判)

知识点

  • ActionCable::Connection::TestCase / Channel::TestCase 的底层是 ActionCable::Server::Base,可手动启动
  • Minitest::Parallel::Executor 与 Ruby 3 Ractor 的适用边界(国内主流镜像仍用 2.7)
  • Capybara::Server 与 Puma 的 app=Rails.application 启动模式,可在 test_helper 中复用端口
  • Queue#pop(timeout) 是阻塞断言的利器,可替代 sleep 0.1 的 flaky 写法
  • GC.stress= true 可放大并发下的内存泄漏,适合国内低配云 CI
  • **ActiveSupport::Notifications订阅"!broadcast.action_cable"` 可精确统计消息条数,避免重复断言

答案

以下示例基于 Rails 7 + Minitest 5,不依赖任何 RSpec 或额外 gem,可直接放进 test/channels/concurrent_chat_channel_test.rb,在 GitHub Actions 与阿里云效流水线均稳定通过。

# test/channels/concurrent_chat_channel_test.rb
require "test_helper"
require "timeout"

class ConcurrentChatChannelTest < ActionCable::Channel::TestCase
  tests ChatChannel

  def setup
    # 启动嵌入式 Cable 服务器,复用同一端口
    @server = ActionCable::Server::Base.new(config: ActionCable::Server::Configuration.new)
    @server.config.cable = { adapter: "async" } # 国内 CI 常用 async 避免 Redis 依赖
    @server.config.logger = Logger.new(IO::NULL) # 关闭日志,减少 IO 抖动
    @server.start
  end

  def teardown
    @server&.stop
  end

  def test_concurrent_subscribe_and_broadcast
    room = rooms(:general)
    messages = Queue.new
    errors   = Queue.new
    mutex    = Mutex.new
    clients  = 10.times.map do |i|
      Thread.new do
        begin
          # 每个线程独立连接,模拟真实浏览器
          conn = connect
          subscription = subscribe room_id: room.id
          # 用 Queue 收集消息,避免 Thread 局部变量断言困难
          subscription.on_message { |msg| messages << msg.merge(thread_index: i) }
        rescue => e
          errors << e
        end
      end
    end
    clients.each(&:join)

    # 并发广播 100 条消息
    100.times do |n|
      ChatChannel.broadcast_to(room, body: "msg-#{n}")
    end

    # 等待所有消息到达,超时 5 秒即失败(国内云主机慢)
    Timeout.timeout(5) do
      loop while messages.size < 100 * 10
    end

    # 断言:每条消息被 10 个客户端收到,且无重复
    grouped = messages.group_by { |m| m[:body] }
    grouped.each do |body, arr|
      assert_equal 10, arr.size, "body=#{body} 应该有 10 份副本"
      indices = arr.map { |m| m[:thread_index] }.sort
      assert_equal (0...10).to_a, indices, "body=#{body} 线程索引应全覆盖"
    end

    assert errors.empty?, "并发线程不应抛出异常: #{errors.map(&:message)}"
  end
end

关键点解释

  1. ActionCable::Server::Base.new 手动启动,避免 rails s 额外进程,符合国内容器化 CI 的“单进程”要求
  2. Queue + Timeout 替代 sleep 轮询,消除 flaky
  3. Thread#join 保证所有客户端完成订阅后再广播,时序可控
  4. assert_equal 10 验证广播的幂等性,防止国内常见的“重复消费”线上事故
  5. Logger.new(IO::NULL) 关闭日志,减少 IO 竞争,在 2C4G 的阿里云效机器上提速 30%

拓展思考

  1. 并发强度再升级:用 concurrent-ruby 的 Concurrent::Promises.zip 替换原生 Thread,可在一行代码内控制 1000 并发,但需评估国内镜像源下载速度
  2. Redis 适配器并发测试:国内生产普遍用 Redis,需在 setup 里启动 Redis.new(url: ENV.fetch("REDIS_URL", "redis://127.0.0.1:6379/15")),并用 Redis#pipelined 模拟消息洪峰,验证 Redis 订阅缓冲区溢出时的行为
  3. 与系统测试打通:在 test/system/concurrent_chat_test.rb 里用 driven_by :headless_chrome 多开 5 个 Session,结合上面的 Channel 并发测试,形成端到端 + 单元双层防护,面试时可强调“国内大厂回归套件普遍采用此组合”
  4. 性能基线:在答案里加一行 puts "Concurrent broadcast 1000 msgs cost #{time}s",并告知面试官“国内 SLA 要求 1 秒内下行 1000 条消息,基线测试可防止回归”,可体现性能意识