In a Rails integration test with turbo-rails, how do you assert a Turbo Stream response and the broadcasts a model sends?
answer
- as: :turbo_stream sets the Accept header
- assert_turbo_stream action:, target:, status:
- it also checks the media type
- assert_turbo_stream_broadcasts with count:
- perform_enqueued_jobs for *_later broadcasts
basics
~10 sSend the request with as: :turbo_stream, then assert_turbo_stream action:, target: (status defaults to :ok); for broadcasts, wrap the change in assert_turbo_stream_broadcasts and run the broadcast jobs with perform_enqueued_jobs.
solid answer
~30 sturbo-rails adds an `as: :turbo_stream` request encoder to integration tests, which sends `Accept: text/vnd.turbo-stream.html,text/html` so `format.turbo_stream` answers. `assert_turbo_stream action: "prepend", target: "tickets"` then asserts the status (default `:ok`), the `text/vnd.turbo-stream.html` media type and a matching `<turbo-stream>` element; a block runs `assert_select` inside it, and `assert_no_turbo_stream` is the negative. For a failed save pass `status: :unprocessable_content`. Broadcasts are checked with `assert_turbo_stream_broadcasts kitchen, count: 1 { ... }`, which reads the broadcasts Action Cable's test helper records. Because `broadcasts_to` sends creates and updates through jobs, the block must run them with `perform_enqueued_jobs`; `capture_turbo_stream_broadcasts` returns the elements for closer checks.
code
ruby · 18 linesclass TicketStreamsTest < ActionDispatch::IntegrationTest
test "a new ticket is prepended to the board" do
post kitchen_tickets_path(kitchens(:main)), as: :turbo_stream,
params: { ticket: { dish: "Risotto", table_number: 7 } }
assert_turbo_stream action: "prepend", target: "tickets" do
assert_select "template article", text: /Risotto/
end
end
test "a blank dish re-renders the form with 422" do
post kitchen_tickets_path(kitchens(:main)), as: :turbo_stream,
params: { ticket: { dish: "" } }
assert_turbo_stream status: :unprocessable_content,
action: "replace", target: "new_ticket"
end
endgo deeper
Recall the pair: as: :turbo_stream on the request, assert_turbo_stream with action: and target: on the response.
Explain what the integration version checks (status, media type, selector), why broadcasts_to's broadcasts need perform_enqueued_jobs, and how capture_turbo_stream_broadcasts exposes attributes.
Design a suite that tests stream responses and broadcasts cheaply at the integration and model level and keeps slow system tests for the few end-to-end paths that need a browser.
Set the testing contract for live updates: which broadcasts are part of a feature's behaviour and must be asserted, and which are incidental and left to a handful of browser tests.
## Two things to test A Turbo Streams feature has two outputs: - the **HTTP response** to the request that changed something (`format.turbo_stream`); - the **broadcasts** sent to other open pages over Action Cable. turbo-rails ships helpers for both and wires them in through load hooks, so a Rails app gets them without an `include`. ## Asking for streams in the request An integration test's request accepts HTML by default, so `respond_to` would take the `format.html` branch. turbo-rails registers a request encoder for `as: :turbo_stream` whose `Accept` header is `text/vnd.turbo-stream.html,text/html`, the same preference Turbo itself sends for a form submission. - `xhr: true` is not a substitute: it adds `X-Requested-With` and an `Accept` that leads with `text/javascript`. - `as: :json` encodes the params as JSON and asks for JSON. ## Asserting the response `assert_turbo_stream` exists in two layers: 1. `Turbo::TestAssertions` (every `ActiveSupport::TestCase`): builds a selector such as `turbo-stream[action="prepend"][target="tickets"]` and runs `assert_select` with `count:` (default 1). A record passed as `target:` is converted with `dom_id`. 2. `Turbo::TestAssertions::IntegrationTestAssertions` (integration tests): first `assert_response status` (default `:ok`) and `assert_equal Mime[:turbo_stream], response.media_type`, then the selector check. Options at a glance: | option | meaning | |---|---| | `action:` | required; the stream's action attribute | | `target:` | an id, or a record turned into `dom_id` | | `targets:` | the CSS selector in a `targets` attribute | | `status:` | integration only; default `:ok` | | `count:` | how many matching elements; default 1 | A block narrows the check to the element's contents: `assert_select "template article", text: /Risotto/`. `assert_no_turbo_stream` takes the same keys and expects zero matches. In Rails 8.1 with Rack 3.1 or later, the 422 symbol is `:unprocessable_content`; `:unprocessable_entity` is Rack's obsolete name. ## Asserting broadcasts When Action Cable and Active Job are loaded, `Turbo::Broadcastable::TestHelper` is included into `ActiveSupport::TestCase`, so integration and model tests both have it. It builds on `ActionCable::TestHelper`, which swaps the server's pub/sub adapter for an in-memory test adapter before each test and records every broadcast by stream name. - `assert_turbo_stream_broadcasts stream, count: n { ... }` accepts a string name or the same objects you pass to `turbo_stream_from`; without `count:` it asserts at least one. - `assert_no_turbo_stream_broadcasts stream { ... }` expects none. - `capture_turbo_stream_broadcasts stream { ... }` returns the broadcast `<turbo-stream>` elements as Nokogiri nodes, so you can check `element["action"]` and `element["target"]`. ## The job trap `broadcasts_to` sends creates and updates with `*_later` methods, which enqueue `Turbo::Streams::ActionBroadcastJob`. `ActiveJob::TestHelper`, which Rails includes into integration tests, switches to the test queue adapter, which keeps jobs in a queue until you run them, so this fails: ```ruby assert_turbo_stream_broadcasts kitchen do kitchen.tickets.create!(dish: "Soup", table_number: 3) end ``` Nothing was broadcast yet, only enqueued. Wrap the change in `perform_enqueued_jobs { ... }` inside the block. Destroys are broadcast synchronously and need no job run. ## Common mistakes 1. Forgetting `as: :turbo_stream`, then reading the html branch's redirect as a broken stream. 2. Leaving out `status:` on a failure test: the default `:ok` makes a correct 422 response fail the assertion. 3. Passing a record as `targets:`: only `target:` converts records with `dom_id`; `targets:` is compared as a literal selector string. 4. Asserting broadcasts without `perform_enqueued_jobs`, then concluding the model does not broadcast. 5. Miscounting: `count:` on `assert_turbo_stream_broadcasts` counts `<turbo-stream>` elements across all payloads, so a broadcast carrying two actions counts twice. ## What these tests do not cover These helpers check markup and messages, not the browser. Whether the ticket actually appears on an open board is a system test's job, with its own helpers for waiting on cable stream sources. ## A balanced suite - one integration test per stream action response, success and failure; - one integration test per broadcast, run through `perform_enqueued_jobs` (a plain `ActiveSupport::TestCase` model test needs `include ActiveJob::TestHelper` first; Rails' railtie adds it to integration tests, not to every test case); - a few system tests for the end-to-end path.
- How do you check which action and target a turbo-rails broadcast used?Use `capture_turbo_stream_broadcasts kitchen { perform_enqueued_jobs { ... } }`. It decodes each payload recorded by Action Cable's test helper and returns the `<turbo-stream>` elements as Nokogiri nodes, so `assert_equal "prepend", streams.first["action"]` and `assert_equal "tickets", streams.first["target"]` read the attributes directly.
- Why does a post without as: :turbo_stream hit the html branch in an integration test?Because the default request does not list `text/vnd.turbo-stream.html` in `Accept`. Rails negotiates `respond_to` from the request's formats, finds `html`, and runs `format.html`, often a redirect. `assert_turbo_stream` would then fail on the status or the media type check before it looks for any element.
- A plain post in an integration test already gets the format.turbo_stream branch.
- assert_turbo_stream checks only the body, never the status or media type.
- assert_turbo_stream_broadcasts sees broadcasts_to's create without running jobs.
- Testing broadcasts requires stubbing ActionCable.server.broadcast by hand.
- xhr: true is how integration tests ask for Turbo Stream responses.
Assumes Rails 8.1 on Rack 3.1+, where 422 is :unprocessable_content, with turbo-rails 2.0 providing the stream assertions.