How do you unit-test a ViewComponent with render_inline, and what do ViewComponent previews add beyond those tests?
answer
- ViewComponent::TestCase over ActiveSupport::TestCase
- returns a Nokogiri HTML5 fragment
- page plus Capybara assertions
- with_request_url and with_variant
- previews at /rails/view_components
basics
~20 srender_inline(AlertComponent.new(...)) renders the component through a test controller's view context, returns a Nokogiri fragment and sets page for Capybara assertions, with no browser or routing. Previews render the same components at /rails/view_components in development for visual review.
solid answer
~40 sA test inherits from `ViewComponent::TestCase` (an `ActiveSupport::TestCase` with `ViewComponent::TestHelpers`). `render_inline(AlertComponent.new(kind: :error, message: "Payment rejected"))` renders through a test controller's view context and returns a `Nokogiri::HTML5` fragment; with Capybara installed it also sets `page`, so `assert_selector("div.alert--error", text: "Payment rejected")` works. Slots are filled with a block, `with_request_url("/claims/7")` and `with_variant(:phone)` set request details, and `refute_component_rendered` checks a `render?` that returned false. These tests take milliseconds because nothing is routed or opened in a browser. A preview class in `test/components/previews` inheriting from `ViewComponent::Preview` defines one public method per example; development serves them at `/rails/view_components` for designers and reviewers, and `render_preview(:default)` reuses an example in a test. In ViewComponent 4 the test controller is set with `vc_test_controller_class`, and preview settings sit under `config.view_component.previews`.
code
ruby · 21 lines# test/components/claim_card_component_test.rb
class ClaimCardComponentTest < ViewComponent::TestCase
test "shows header and one action" do
claim = Claim.new(id: 7, number: "CL-0007", summary: "Water damage")
with_request_url "/claims/7" do
render_inline(ClaimCardComponent.new(claim: claim)) do |card|
card.with_header { "Claim CL-0007" }
card.with_action(label: "Approve", url: "/claims/7/approve")
end
end
assert_selector "article.claim-card header", text: "Claim CL-0007"
assert_selector "footer", text: "Approve"
end
test "preview example renders" do
render_preview(:default)
assert_selector "article.claim-card"
end
endgo deeper
Know that components are tested with render_inline and Capybara-style selectors, and where preview classes live.
Explain the test controller and view context, the Nokogiri return value versus page, and the helpers for slots, URLs and variants.
Shape a test pyramid where components carry markup tests, system tests stay few, and previews double as fixtures; handle the v4 config moves.
Decide whether a component catalogue is a product for designers and other teams, and what it costs to keep every state previewed.
## Why components are easy to test A partial is usually tested through a controller or system test: route, controller, database, layout and then a selector. A **ViewComponent** is a Ruby object with explicit inputs, so it can be rendered on its own and its HTML inspected directly. That is what `render_inline` does. ## A render_inline test ```ruby class AlertComponentTest < ViewComponent::TestCase test "error alert shows the message" do render_inline(AlertComponent.new(kind: :error, message: "Payment rejected")) assert_selector "div.alert.alert--error[role=alert]", text: "Payment rejected" end test "renders nothing without a message" do render_inline(AlertComponent.new(kind: :info, message: "")) refute_component_rendered end end ``` What happens underneath: 1. `ViewComponent::TestCase` is an `ActiveSupport::TestCase` that includes **`ViewComponent::TestHelpers`**; an RSpec suite includes the same module. 2. `render_inline(component, &block)` builds a view context from a **test controller** (`ApplicationController` unless `vc_test_controller_class` returns another) and calls Rails' `render` on the component. 3. It returns a **`Nokogiri::HTML5`** fragment (HTML5 parsing since ViewComponent 4), so `.css("div.alert").text` works. 4. When Capybara is loaded, `page` wraps the output in `Capybara::Node::Simple`, enabling `assert_selector`, `assert_text` and their `refute_` forms. `assert_component_rendered` and `refute_component_rendered` check whether anything came out at all. ## Controlling the rendering context - **Slots and content**: pass a block, `render_inline(ClaimCardComponent.new(claim: claim)) { |card| card.with_header { "Claim 7" } }`. - **Request path**: `with_request_url("/claims/7") { render_inline(...) }` for components that highlight the current page; `host:`, `method:` and `protocol:` are optional. - **Variants and formats**: `with_variant(:phone) { ... }` and `with_format(:json) { ... }` choose among `alert_component.html+phone.erb`-style templates. - **Controller**: override `vc_test_controller_class` to render under a different controller, for example one with extra helper modules. These tests touch no router and no browser, and the database only if the component itself queries, so a suite of hundreds runs in seconds. ## Previews A **preview** is a class of examples: ```ruby # test/components/previews/alert_component_preview.rb class AlertComponentPreview < ViewComponent::Preview def warning render(AlertComponent.new(kind: :warning, message: "Upload the police report")) end end ``` - Each public method is one example; `render` here records what to render rather than rendering immediately. - Previews are served at **`/rails/view_components`**, enabled by default only in **development and test**. - They are a visual catalogue: designers and reviewers see every state of the alert box or claim card without clicking through the portal to reach it. - `render_preview(:warning)` in `AlertComponentTest` renders that example, so the catalogue and the tests stay in step. - A preview can use a template under `alert_component_preview/` and a `layout`, and can accept params for interactive examples. | Tool | Answers | Runs | |---|---|---| | `render_inline` test | does this input produce this HTML? | in the test suite, in milliseconds | | preview | what does each state look like? | in the browser, in development | | system test | does the page work end to end? | in a real browser, slowest | ## ViewComponent 4 changes for tests and previews - `config.view_component.test_controller` was replaced by the **`vc_test_controller_class`** helper method. - Preview options moved under **`config.view_component.previews`**: `paths`, `route`, `enabled`, `default_layout`, `controller`. - Test helpers parse with **HTML5** rules, so assertions written against HTML4 parsing quirks can change. ## Mistakes interviewers listen for 1. **"Components need a browser to test."** `render_inline` runs in process through a test controller; only system tests need a browser. 2. **"render_inline returns a string."** It returns a Nokogiri fragment, and `rendered_content` holds the raw output if you need it. 3. **"Previews ship to production."** They are enabled by default only in development and test. 4. **"Testing previews replaces unit tests."** `render_preview` checks that an example renders; assertions about each input still belong in `render_inline` tests. A senior answer connects the pieces: unit tests per component, previews as a shared catalogue reused by those tests, and a thin layer of system tests for the flows that wire components together.
- What does render_inline return, and how is that different from page?`render_inline` returns a `Nokogiri::HTML5` fragment of the output, which you can query with `.css`. `page` is a `Capybara::Node::Simple` over the same HTML, available when Capybara is installed, and it is what `assert_selector` and `assert_text` use.
- Why might a team keep previews even with full render_inline coverage?Tests prove that inputs produce the expected markup; they do not show how it looks. Previews let designers and reviewers see every state of a component in a browser, and `render_preview` reuses those examples in tests so the two do not drift apart.
- render_inline needs a system test and a running browser
- render_inline returns the HTML as a plain String only
- Previews are served in production at /rails/view_components by default
- config.view_component.test_controller still sets the test controller in v4
- A component must be routed before it can be tested
Assumes ViewComponent 4.15 on Rails 8.1: vc_test_controller_class, the previews.* config namespace and Nokogiri::HTML5 parsing in test helpers all date from ViewComponent 4.0.