如何在RSpec/Capybara视图测试中查看渲染页面?
save_and_open_page for Rails View Tests (Non-Feature Tests) Great question! I’ve hit this exact roadblock before—save_and_open_page is such a lifesaver in feature tests for quick visual debugging, so it’s annoying when it throws that NameError in view tests. The good news is there are a few clean, convenient workarounds that don’t require rolling your own full implementation from scratch.
Here are my go-to solutions:
1. Use Ruby’s built-in save_and_open_file with rendered
Rails view tests automatically expose a rendered variable that holds the full HTML output of your rendered view. You can pass this directly to Ruby’s standard library save_and_open_file method to generate and open a temporary HTML file:
save_and_open_file(rendered, 'tmp/view_test_render.html')
This will save the rendered HTML to your project’s tmp directory and open it in your default browser automatically. No extra gems needed—just plain Ruby and Rails functionality.
2. Launch the rendered HTML directly in your browser with launchy
If you already have the launchy gem installed (it’s a common dependency for Capybara), you can skip writing to a file entirely and open the HTML directly in your browser:
require 'launchy' Launchy.open("data:text/html,#{URI.encode(rendered)}")
To make this even more convenient, wrap it in a helper method so you can call it with a single line in any view test. Add this to your test/test_helper.rb:
module ViewTestDebugHelpers def save_and_open_view require 'launchy' Launchy.open("data:text/html,#{URI.encode(rendered)}") end end # Include the helper in your view test class class ActionView::TestCase include ViewTestDebugHelpers end
Now you can just call save_and_open_view in any view test, and it’ll pop open the rendered HTML instantly—just like save_and_open_page for feature tests.
3. (Optional) Bring in Capybara’s DSL to view tests
If you don’t mind adding a bit more setup, you can include Capybara’s methods directly in your view tests. Add this to your test_helper.rb:
class ActionView::TestCase include Capybara::DSL end
This will let you use save_and_open_page, but you’ll need to make sure you’ve rendered the view first and assign the rendered content to Capybara’s page object (you might need to run page.body = rendered before calling the method). That said, this is a bit heavier than the first two options, so I usually stick with the simpler approaches unless I need more Capybara functionality in my view tests.
All of these methods let you get that quick visual feedback without having to manually inspect the rendered string or build a custom solution from scratch.
内容的提问来源于stack exchange,提问作者Arepo

