Lesson 7 — Testing Phlex views in Rails
Testing in a Rails context differs from the standalone Minitest approach in Module 3 in one important way: views and components that use Rails helpers (routes, link_to, current_user etc.) need a view context to render correctly.
Component unit tests
For components that don’t use Rails helpers, the Module 3 approach works unchanged:
|
|
For components that use Rails helpers, provide a view context:
|
|
Include it in your test classes:
|
|
View tests
Views are also just Ruby objects — test them the same way:
|
|
System tests
For full end-to-end testing with a browser, Rails system tests work exactly as normal — Phlex views are just HTML from the browser’s perspective:
|
|
What to test at each level
| Level | What to test | Tools |
|---|---|---|
| Component unit | Props, variants, slots, type validation | Minitest + Nokogiri |
| View unit | Data rendering, empty states, conditional sections | Minitest + Nokogiri |
| System | User flows, navigation, form submission | Capybara |
The component and view unit tests are fast — no browser, no HTTP, just Ruby objects. Save system tests for the flows that matter most.
Exercise
Write unit tests for Views::Boards::Index:
- Empty state renders when
boards:is empty - Board names render when boards are present
- The “New Board” link is present
Module 4 summary
bundle add phlex-railsandrails generate phlex:installsets up theViews::andComponents::namespaces with Zeitwerk autoloading- Remove all
require_relativefrom component files — Zeitwerk handles loading - Two approaches: full Phlex (greenfield, all ERB deleted) or hybrid (ERB + Phlex components, best for migration)
- Hybrid is a legitimate long-term architecture and the recommended migration path for existing apps
- Three layout approaches: composition, inheritance via
around_template, and legacy ERB compatibility — KanbanFlow usesaround_template layout falseinApplicationControllerdisables Rails’ built-in layout system- Controllers render views explicitly:
render Views::Boards::Index.new(boards:) - No implicit instance variables — data is passed through
initialize - Rails helpers use adapters — include only what you need, starting with
Phlex::Rails::Helpers::Routes - Never
includeRails helper modules directly — use adapters orregister_value_helper/register_output_helper bin/devruns Rails server and Tailwind watcher together- Component unit tests work as in Module 3; add a view context for components that use Rails helpers
KanbanFlow built this module
Components::Layouts::AppLayout— full application shellViews::Boards::Index— board listing with empty stateViews::Boards::Show— placeholderComponents::EmptyState— reusable empty state component- All
Phlex::UIcomponents restyled with Tailwind