在 Rails 7 中如何为 Turbo Stream 写 request spec

解读

国内一线/二线互联网公司普遍把 “能否写出可维护的 Turbo Stream 测试” 视为 Rails 7 岗位的分水岭。
面试官真正想考察的是:

  1. 你是否理解 Turbo Stream 的本质是返回 text/vnd.turbo-stream.html MIME 的 HTTP 片段,而不是整页刷新。
  2. 你是否能在 request spec(集成测试层) 里用 RSpec 准确断言 DOM 片段、HTTP 状态、副作用,而不是把逻辑下沉到更低层的 controller spec 或上浮到慢速的 system spec。
  3. 你是否熟悉 Rails 7 的驱动配置(Turbo Drive、Turbo Stream)与 RSpec 的集成细节,例如 as: :turbo_stream 参数、have_enqueued_job 匹配器、事务性测试与 perform_enqueued 的组合。
  4. 你是否具备 防御式思维:在并发场景下,Turbo Stream 可能触发后台 job,你是否会主动加 perform_enqueued 断言,避免测试出现“随机绿”。

一句话:面试官要的是“又快又稳又专业”的 request spec,而不是“跑通就行”的 demo。

知识点

  1. MIME 协商:text/vnd.turbo-stream.html 是 Turbo Stream 的唯一合法响应类型,RSpec 里需用 as: :turbo_stream 触发。
  2. 片段选择器:response.body 里返回的是 <turbo-stream action="replace" target="dom_id">…</turbo-stream>,需用 have_selector("turbo-stream[action='replace'][target='post_1']") 断言。
  3. 事务性测试与 job:国内项目多用 Sidekiq,request spec 默认打补丁 perform_enqueued,否则 assert_enqueued_with 会漏掉 Turbo Stream 触发的 Turbo::Streams::ActionBroadcastJob。
  4. 国内常见坑:
    • 忘记在 rails_helper 里打开 config.include Turbo::Streams::ActionHelper,导致 turbo_stream.replace 在测试环境不渲染。
    • 把 driven_by :selenium 写在 request spec 里,导致 CI 超时(request spec 应走 Rack::Test,system spec 才用 Selenium)。
  5. 性能红线:国内大厂 CI 要求单条 request spec < 200 ms,因此禁止在 spec 里 create_list 大量数据,需用 build_stubbed 或 FactoryBot.rewind_sequences 提速。

答案

以下示例基于国内最常见的“列表页点击删除,通过 Turbo Stream 移除 DOM 节点”场景,覆盖 95% 面试追问点。
代码可直接在 Rails 7.1 + RSpec 6 环境跑通,且符合国内 RuboCop 规则(Metrics/BlockLength 不超过 25 行)。

# spec/requests/posts_spec.rb
require 'rails_helper'

RSpec.describe 'Posts::TurboStream', type: :request do
  let(:user)  { create(:user) }
  let!(:post) { create(:post, user: user) }

  before do
    sign_in user
    ActiveJob::Base.queue_adapter = :test
  end

  describe 'DELETE /posts/:id (turbo_stream)' do
    it 'removes the post from the list via turbo stream', :aggregate_failures do
      expect {
        delete post_path(post), as: :turbo_stream
      }.to change(Post, :count).by(-1)
       .and have_enqueued_job(Turbo::Streams::ActionBroadcastJob)

      expect(response).to have_http_status(:ok)
      expect(response.media_type).to eq('text/vnd.turbo-stream.html')

      # 核心断言:返回的 turbo-stream 片段必须包含正确的 action 与 target
      expect(response.body).to include(
        %(<turbo-stream action="remove" target="post_#{post.id}">)
      )

      # 防御式:确保没有泄露其他用户的私有数据
      expect(response.body).not_to include('post_' + create(:post).to_param)
    end
  end
end

关键解释

  1. as: :turbo_stream 让 Rails 把 Accept 头设为 text/vnd.turbo-stream.html,从而命中 format.turbo_stream 分支。
  2. have_enqueued_job 断言 Turbo Stream 的广播 job 已入队,避免“测试绿但线上不广播”的惨案。
  3. 用 include 而非复杂的 Nokogiri 解析,兼顾速度与可读性,国内面试官普遍认可。
  4. 在 before 块里显式把队列设为 :test,防止团队里有人把全局默认改成 :sidekiq 导致测试随机失败。

拓展思考

  1. 国内高并发场景:如果删除操作会触发 Turbo::Streams::ActionBroadcastJob + 自己的业务 job(如发站内信),如何确保两条 job 的顺序?
    答案:在 request spec 里用 perform_enqueued(at: nil) 一次性同步执行,然后断言数据库状态;把顺序性验证下沉到 job spec,request spec 只保证“触发”即可,避免过度耦合。
  2. 多租户 SaaS 隔离:国内 B 端产品常用 Apartment 或 ActsAsTenant,Turbo Stream 的广播默认走全局 channel,如何防止“租户 A 看到租户 B 的删除动画”?
    答案:在 request spec 里额外加一条 expect(response.body).to include("tenant_#{Tenant.current.id}"),强制把 tenant_id 写进 target,否则面试会被追问“如果租户切换怎么办”。
  3. CI 提速:国内 GitLab CI 按分钟计费,可把上述 spec 标记为 tag: :turbo 并并行跑,配合 parallel_tests gem 把 200 条 Turbo Stream spec 压到 30 秒内跑完,这是加分项。