Skip to content

Commit

Permalink
Make render_in_view_context forward its args to the block (#1616)
Browse files Browse the repository at this point in the history
  • Loading branch information
camertron committed Jan 3, 2023
1 parent b0e4f76 commit 66b443a
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 6 deletions.
1 change: 1 addition & 0 deletions .standard.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ruby_version: 2.5
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ nav_order: 5

## main

* Modify the `render_in_view_context` test helper to forward its args to the block.

*Cameron Dutro*

## 2.80.0

* Move system test endpoint out of the unrelated previews controller.
Expand Down
14 changes: 8 additions & 6 deletions lib/view_component/test_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,21 +99,23 @@ def render_preview(name, from: preview_class, params: {})
Nokogiri::HTML.fragment(@rendered_content)
end

# Execute the given block in the view context. Internally sets `page` to be a
# `Capybara::Node::Simple`, allowing for Capybara assertions to be used:
# Execute the given block in the view context (using `instance_exec`).
# Internally sets `page` to be a `Capybara::Node::Simple`, allowing for
# Capybara assertions to be used. All arguments are forwarded to the block.
#
# ```ruby
# render_in_view_context do
# render(MyComponent.new)
# render_in_view_context(arg1, arg2:) do |arg1, arg2:|
# render(MyComponent.new(arg1, arg2))
# end
#
# assert_text("Hello, World!")
# ```
def render_in_view_context(&block)
def render_in_view_context(*args, &block)
@page = nil
@rendered_content = controller.view_context.instance_exec(&block)
@rendered_content = controller.view_context.instance_exec(*args, &block)
Nokogiri::HTML.fragment(@rendered_content)
end
ruby2_keywords(:render_in_view_context) if respond_to?(:ruby2_keywords, true)

# @private
def controller
Expand Down
11 changes: 11 additions & 0 deletions test/sandbox/test/rendering_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ def test_render_in_view_context
assert_selector("div", text: "hello,world!")
end

def test_render_in_view_context_forwards_arguments
@foo = "foo"
@bar = "bar"

render_in_view_context(@foo, bar: @bar) do |foo, bar:|
render(MyComponent.new) { foo + bar }
end

assert_text "hello,world!\nfoobar"
end

def test_render_inline_returns_nokogiri_fragment
assert_includes render_inline(MyComponent.new).css("div").to_html, "hello,world!"
end
Expand Down

0 comments on commit 66b443a

Please sign in to comment.