Last active
December 30, 2023 03:06
-
-
Save borama/321e733b6b75a6d6f3fcbe3569e99322 to your computer and use it in GitHub Desktop.
Previewing Simple Form form (or any Rails template in general) in Lookbook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/ spec/components/previews/forms/simple_form_preview/basic_form.html.slim | |
= simple_form_for(mail_search_object, url: "/fake/search") do |f| | |
= f.input :to | |
= f.input :subject, hint: "Explanation for this field" | |
= f.button :submit, "Search" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/components/previews/forms/simple_form_preview.rb | |
class Forms::SimpleFormPreview < ViewComponent::Preview | |
def basic_form | |
mail_search = MailSearch.new | |
# simulate an error message in the form | |
mail_search.errors.add(:subject, :not_blank, message: "Subject must not be blank") | |
render_with_template(locals: { mail_search_object: mail_search }) | |
end | |
# This inner class serves us to prepare an ActiveRecord object for the form | |
class MailSearch | |
include ActiveModel::Model | |
attr_accessor :to, :subject | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To preview any Rails template in Lookbook, just do the following:
test
folder)render_with_template
(which is a View Component method) and pass the data as local variables to the templateMore context in this post: From partials to ViewComponents: writing reusable front-end code in Rails.