Skip to content

Commit

Permalink
Add support for render_previews in RSpec tests
Browse files Browse the repository at this point in the history
  • Loading branch information
thutterer committed Jul 11, 2022
1 parent 325a55a commit 4c2c84d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ title: Changelog

## main

* Add support for `render_preview` in RSpec tests.

*Thomas Hutterer*

* Switch to `standardrb`.

*Joel Hawksley*
Expand Down
14 changes: 12 additions & 2 deletions lib/view_component/render_preview_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,25 @@ module RenderPreviewHelper
# ```
#
# Note: `#rendered_preview` expects a preview to be defined with the same class
# name as the calling test, but with `Test` replaced with `Preview`:
# name as the calling test, but with "Test" replaced with "Preview":
#
# MyComponentTest -> MyComponentPreview etc.
#
# With RSpec it uses `described_class` plus "Preview" as the class name.
#
# @param preview [String] The name of the preview to be rendered.
# @return [Nokogiri::HTML]
def render_preview(name)
begin
preview_klass = self.class.name.gsub("Test", "Preview")
preview_klass = if respond_to?(:described_class)
if described_class.nil?
raise "`render_preview` expected a described_class, but it is nil."
end

"#{described_class}Preview"
else
self.class.name.gsub("Test", "Preview")
end
preview_klass = preview_klass.constantize
rescue NameError
raise NameError.new(
Expand Down
25 changes: 25 additions & 0 deletions test/sandbox/spec/components/previews/preview_component_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
describe PreviewComponent do
include ViewComponent::RenderPreviewHelper

before do
ViewComponent::Preview.load_previews
end

it "renders the preview" do
render_preview(:default)

expect(page).to have_css "h1", text: "Lorem Ipsum"
end
end

describe "PreviewComponent" do
include ViewComponent::RenderPreviewHelper

before do
ViewComponent::Preview.load_previews
end

it "raises an error" do
expect { render_preview(:default) }.to raise_error(/expected a described_class/)
end
end

0 comments on commit 4c2c84d

Please sign in to comment.