How to use helpers in a component and still have previews work? #1451
-
First, let me say that I've read #955, but I can't see how to apply it in this case. I want to test, in a component test, that a component renders another component; I don't want that test to have to know what that sub-component outputs. I've been reading #1382, and decided to apply a I've added this to application_helper.rb: def test_selector(value)
return '' unless Rails.env.development? || Rails.env.test?
"data-test-selector='#{strip_tags value}'".html_safe
end and, in the component's .html.erb file: <div <%= helpers.test_selector('header-login') %> class="flex flex-col items-end">
…
</div> This works perfectly — until I try to preview the component, in which case I get a NoMethodError:
Adding As far as I can see, the solution in #955 involves extensive modifications to each component's class, which doesn't scale for this. Simply adding the attribute to the component rather than using a helper doesn't help, as then it will appear in production. If I was using Webpack or similar, I could have it strip the attribute in the production bundle, but I'm using importmaps. #1093 looks like it's asking for something similar, but one of the suggested solutions is a hack that will break if sprockets-rails changes its railtie, and another is explicitly disallowing view helpers in previews. If that route's taken, I'll still need a workaround, as I need to use them here. Is there a simple way to get helpers working in previews without having to perform massive hacks? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
…and, a few minutes later, inspiration strikes 🙄 Adding the following as lib/view_component_preview.rb solves the problem. Hopefully this monkey-patch doesn't break anything else, but I've not tested it fully yet… # frozen_string_literal: true
class ViewComponent::Preview
include Rails.application.routes.url_helpers
end |
Beta Was this translation helpful? Give feedback.
…and, a few minutes later, inspiration strikes 🙄
Adding the following as lib/view_component_preview.rb solves the problem. Hopefully this monkey-patch doesn't break anything else, but I've not tested it fully yet…