Register a callable to decode rendered content for a given MIME type
Each registered decoder will also define a `#rendered.$MIME` helper
method, where `$MIME` corresponds to the value of the `mime` argument.
=== Arguments
`mime` - Symbol the MIME Type name for the rendered content
`callable` - Callable to decode the String. Accepts the String
value as its only argument
`block` - Block serves as the decoder when the
`callable` is omitted
By default, ActionView::TestCase defines a decoder for:
* :html - returns an instance of Nokogiri::XML::Node
* :json - returns an instance of ActiveSupport::HashWithIndifferentAccess
Each pre-registered decoder also defines a corresponding helper:
* :html - defines `rendered.html`
* :json - defines `rendered.json`
=== Examples
To parse the rendered content into RSS, register a call to `RSS::Parser.parse`:
```ruby
register_decoder :rss, -> rendered { RSS::Parser.parse(rendered) }
test "renders RSS" do
article = Article.create!(title: "Hello, world")
render formats: :rss, partial: article
assert_equal "Hello, world", rendered.rss.items.last.title
end
```
To parse the rendered content into a Capybara::Simple::Node,
re-register an `:html` decoder with a call to
`Capybara.string`:
```ruby
register_decoder :html, -> rendered { Capybara.string(rendered) }
test "renders HTML" do
article = Article.create!(title: "Hello, world")
render partial: article
rendered.html.assert_css "h1", text: "Hello, world"
end
```
Motivation / Background
---
While the `ActionView::TestCase` class isn't marked with a `:nodoc:`
comment to indicate that it's internal to Rails, there isn't much
content in the guides that explains how to test view partials.
Libraries like
[view_component](https://github.com/ViewComponent/view_component/) have
[built-in support for
testing](https://viewcomponent.org/guide/testing.html), including
Capybara integration.
While `ActionView::TestCase` already integrates with
`rails-dom-testing`, that integration could be better documented.
Additionally, it wouldn't take much for consuming applications to mimic
the ViewComponent testing experience for their Action View Partials.
Details
---
First, link to the "Testing Rails Applications" page from the
`ActionView::TestCase` class documentation.
Next, add a "Testing View Partials" section to the guides that expands
upon the variety of tooling available to tests that inherit from
`ActionView::TestCase`. In that section, cover topics like:
* the `render` helper method
* the `rendered` helper attribute reader
* calls to `assert_select` with attribute placeholders
* the `document_root_element` helper method
* integration with Ruby's Pattern Matching
* opportunities to integrate with Capybara
Additional Information
---
Additionally, add test coverage that exercise the examples shared in the
new section, including:
* Calls to `assert_select` that utilize attribute placeholders
* Ruby 3.0's Pattern Matching
* Integration with Capybara
The existing content_tag tests document how to use content_tag outside
of erb views with data attributes. But for those who need to use
content_tag with nested content_tags and data attributes outside of
erb views, it can be challenging to find out how to do that.
When I had to do this in a project, it took me longer than I wanted.
Hopefully adding this test with an explicit example of how to achieve that
will others some time.
Fix: https://github.com/rails/rails/issues/48173
If for some reason the column identification fails, we should
fallback to the old error rendering with only line information.
https://github.com/rails/rails/pull/31250 optimised rendering a collection with `cached: true`, but also with `cached: proc {}`. The problem is the proc may reference associations that should be preloaded to avoid n+1s in generating the cache key.
For example:
```ruby
@posts = Post.preload(:author)
@view.render partial: "test/partial", collection: @post, cached: proc { |post| [post, post.author] }
```
This will n+1 on `post.author`.
To fix this, this PR will always preload the collection if there's a proc given for `cached`. `cached: true` will still not preload unless it renders, as it did in https://github.com/rails/rails/pull/31250.
Ruby 3.1 introduced an optimization to string interpolation for some
core classes in b08dacfea3.
But since we override `to_s` in some of those core classes to add behavior
like `to_s(:db)`, all Rails applications will not be able to take advantage
of that improvement.
Since we can use the `to_formatted_s` alias for the Rails specific behavior
it is best for us to deprecate the `to_s` core extension and allow Rails
applications to get the proformace improvement.
This commit starts removing all the `to_s(:db)` calls inside the framework
so we can deprecate the core extension in the next commit.
Caching something that shouldn't be cached is a potential source of
bugs and security vulnerabilities. For example, one could write a
form helper that outputs a request-specific auth token, only for
the helper to be used inside of a `cache` block.
In the GitHub application, we implemented a caching? method and used
it to raise an error if a specific code path is being cached that
we don't want to be cached.
I've credited its original author, @btoews.
Co-authored-by: Ben Toews <mastahyeti@gmail.com>
Co-authored-by: John Hawthorn <jhawthorn@github.com>
Co-authored-by: Kasper Timm Hansen <kaspth@gmail.com>
Instead of using the ERBTracker, we can use RipperTracker which is extracted from https://github.com/jhawthorn/actionview_precompiler.
Using a parser finds dependencies that would otherwise be difficult to find with the regular expressions. It should also theoretically work with other template systems since it operates on the compiled template instead of the contents of the file.
Co-authored-by: John Hawthorn <john@hawthorn.email>
In https://github.com/rails/rails/pull/37919, support
for rendering objects that respond_to render_in in
controllers was added. However, the implementation
did not support layouts.
This change updates the implementation from #37919
to more closely match the rest of the
ActionView::Template classes, enabling the use of layouts.
Co-authored-by: Felipe Sateler <fsateler@gmail.com>
When rendering a view with annotate_rendered_view_with_filenames
enabled, we were inserting newlines after the BEGIN and END
comments. These newlines are not ideal in some use cases, such
as rendering templates to strings that are then passed around
our application.
As the newlines were added for aesthetic purposes, we think it
makes sense to remove them so that rendered template strings do
not contain extraneous newlines.
As a result of removing these newlines, the annotations
no longer affect the reporting of template error on the correct
line, as addressed in #38950. As such, we've reverted those
changes as well.
Co-authored-by: Chris Gavin <chrisgavin@github.com>
This commit extends the `ActionView::Helpers#translate` (and by way of
alias, `#t`) helper methods to accept blocks.
When invoked with a block, the `translate` call will yield the
translated text as its first block argument, along with the resolved
translation key as its second:
```erb
<%= translate(".key") do |translation, resolved_key| %>
<span data-i18n-key="<%= resolved_key %>"><%= translation %></span>
<% end %>
```
In cases where relative translation keys are foregone in lieu of fully
qualified keys, or if the caller is not interested in the resolved key,
the second block argument can be omitted:
```erb
<%= translate("action.template.key") do |translation| %>
<p><%= translation %></p>
<p><%= translation %>, but a second time</p>
<% end %>
```
A benefit of yielding the translation is that it enabled template-local
variable re-use. Alternatively, [`Object#tap`][tap] could be used.
Prior to this commit, however, the resolution of the translation key was
internal to `ActionView`, and unavailable to the caller (unless they
were willing to explicitly determine the resolved key themselves). By
making it available as a block parameter, it could be used to annotate
the translated value in the resulting elements.
[tap]: https://ruby-doc.org/core-2.7.0/Object.html#method-i-tap
When rendering a template with an explicit JS format, typically via
`respond_to :js`, we want to be able to render HTML partials without
having to specify their format, in order to make SJR more ergonomic.
A Rails view may rely on several templates (e.g. layouts and partials)
in addition to the template for the action being rendered (e.g.
"show.html.erb"). To track which view file is currently being rendered
for the purpose of generating template tree digests used in cache
fragment keys, Action View uses a stack, the top item of which is
accessed via the @current_template variable (introduced in 1581cab).
Consider the following template:
<!-- home.html.erb -->
<%= render layout: "wrapper" do %>
<%= cache "foo" %>
HOME
<%= end %>
<%= end %>
Inside the block passed to the render helper, @current_template
corresponds to the wrapper.html.erb template instead of home.html.erb.
As wrapper.html.erb is then used as the root node for generating the
template tree digest used in the cache fragment key, the cache fragment
fails to expire upon changes to home.html.erb. Additionally, should a
second template use the wrapper.html.erb layout and contain a cache
fragment with the same key, the cache fragment keys for both templates
will be identical - causing cached content to "leak" from one view to
another (as described in #38984).
This commit skips adding templates to the stack when rendered as a
layout with a block via the render helper, ensuring correct and unique
cache fragment digests. Additionally, the virtual_path keyword arguments
found in CacheHelper and all references to the are removed as they no
longer possess any function. (Following the introduction of
@current_template, virtual_path is accessed via
@current_template.virtual_path rather than as a standalone variable.)
This is because we only use hash to maintain the result. So when the key
are the same, the result would be skipped. The solution is to maintain
an array for tracking every item's position to restructure the result.
Many tests were using `render file:`, but were only testing the
behaviour of `render template:` (file: just allows more paths/ is less
secure then template:).
The reason for so many `render file:` is probably that they were the old
default.
This commit replaces `render file:` with `render template:` anywhere the
test wasn't specifically interested in using `render file:`.
* Global ignores at toplevel .gitignore
* Component-specific ignores in each toplevel directory
* Remove `actionview/test/tmp/.keep` for JRuby
```
rm actionview/test/tmp/ -fr
cd actionview/
bundle exec jruby -Itest test/template/digestor_test.rb
```
Related to #11743, #30392.
Closes#29978.
When rendering heterogeneous collection using `render @collection` or
`render partial: @collection`, the expected `<partial_name>_iteration`
variable is missing due to `find_template` not having the name of the
iteration variable included in its cache keys.
In #26672 we blocked use of Ruby keywords as identifiers for view
locals but inadvertently broke the use of instance variable names
as identifiers. Whilst not explicitly documented this behavior has
been around for a long time and there's no need to break it now.
Fixes#27480.