Skip to content

Instantly share code, notes, and snippets.

@borama
Last active December 30, 2023 03:06
Show Gist options
  • Save borama/321e733b6b75a6d6f3fcbe3569e99322 to your computer and use it in GitHub Desktop.
Save borama/321e733b6b75a6d6f3fcbe3569e99322 to your computer and use it in GitHub Desktop.
Previewing Simple Form form (or any Rails template in general) in Lookbook
/ 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"
# 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
@borama
Copy link
Author

borama commented Jun 16, 2022

To preview any Rails template in Lookbook, just do the following:

  • create a View Component preview file in the standard location (we use RSpec here but the same applies for Minitest, the files are just located under the test folder)
  • create a separate preview template with the same name as the preview method in a subfolder named according the preview file
  • in the preview file, prepare any data you need to show in your preview template
  • use render_with_template (which is a View Component method) and pass the data as local variables to the template
  • of course, you can use all Lookbook annotations to further describe and document the preview

More context in this post: From partials to ViewComponents: writing reusable front-end code in Rails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment