|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "bundler/setup" |
| 4 | +require "minitest/autorun" |
| 5 | +require "minitest/mock" |
| 6 | +require "rails" |
| 7 | +require "action_controller/railtie" |
| 8 | +require "active_support/testing/isolation" |
| 9 | +require "view_component" |
| 10 | + |
| 11 | +# Boots a fresh application per test in a forked process, so tests can choose |
| 12 | +# their own environment. Runs separately from the sandbox, which boots in test. |
| 13 | +class TemplateCachingTest < ActiveSupport::TestCase |
| 14 | + include ActiveSupport::Testing::Isolation |
| 15 | + |
| 16 | + def test_executor_checks_for_template_changes_when_templates_are_not_cached |
| 17 | + app = boot_app("development") |
| 18 | + refute ActionView::Base.cache_template_loading |
| 19 | + |
| 20 | + watcher = Minitest::Mock.new |
| 21 | + watcher.expect(:execute_if_updated, nil) |
| 22 | + ViewComponent::CompileCache.stub(:template_watcher, watcher) { app.executor.wrap {} } |
| 23 | + |
| 24 | + watcher.verify |
| 25 | + end |
| 26 | + |
| 27 | + # Non-main Ractors can't read ActionView::Resolver's class variable on Ruby 4.0, |
| 28 | + # so the executor must not read it on every request when templates are cached. |
| 29 | + def test_executor_does_nothing_when_templates_are_cached |
| 30 | + app = boot_app("production") |
| 31 | + assert ActionView::Base.cache_template_loading |
| 32 | + |
| 33 | + reads = 0 |
| 34 | + ActionView::Resolver.singleton_class.prepend(Module.new do |
| 35 | + define_method(:caching?) do |
| 36 | + reads += 1 |
| 37 | + super() |
| 38 | + end |
| 39 | + end) |
| 40 | + ViewComponent::CompileCache.stub(:template_watcher, ->(*) { flunk "templates were watched" }) { app.executor.wrap {} } |
| 41 | + |
| 42 | + assert_equal 0, reads |
| 43 | + end |
| 44 | + |
| 45 | + private |
| 46 | + |
| 47 | + def boot_app(env) |
| 48 | + Rails.env = env |
| 49 | + |
| 50 | + Class.new(Rails::Application) do |
| 51 | + config.root = __dir__ |
| 52 | + config.eager_load = env == "production" |
| 53 | + config.enable_reloading = env == "development" |
| 54 | + config.secret_key_base = "test" |
| 55 | + config.logger = Logger.new(nil) |
| 56 | + end.tap(&:initialize!) |
| 57 | + end |
| 58 | +end |
0 commit comments