ruby-on-rails 如何确保在测试模式(RSpec)下使用Rail 7、csssling-rails、jssling-rails时存在资产?

hgb9j2n6  于 5个月前  发布在  Ruby
关注(0)|答案(3)|浏览(72)

我正在将一个大型的商业(专有)Rails 6应用程序升级到Rails 7。我们从来没有使用过Webpacker,而是直接从Bootstrap之类的捆绑gem升级到“Rails 7方式”。
事实证明,Rails 7的“无Node”工作流对于同时包含CSS和JS组件的组件没有很好的解决方案。在我们的案例中,最明显的违规者是Bootstrap。面对通过导入Map维护Bootstrap的JS“一半”,以及通过类似旧的Bootstrap gem或手动调试维护CSS“一半”的问题,(是的,有really is no other solution without Node here)我们最终回到了完整的Node工作流。
所有提供CSS和/或JS的前端组件都已经可以在NPM中愉快地使用,所以现在都通过package.json和Yarn进行管理,bin/dev驱动Sass和esbuild编译从app/assetsapp/javascriptnode_modules/...提取的SCSS和JS组件;因此,资产管道manifest.js仅包含对app/assets内的buildimages文件夹的引用。
这感觉有点倒退,所有重量级的手动维护文件名列表(不再支持导入),沿着的是现在在Foreman下运行的多个进程的复杂性,而不是在每个请求的基础上在Sprockets中同步处理事情,但随着所有这些东西都被弃用/放弃,显然是时候更新了。
这一切在开发和生产模式下都很好,但是测试呢?我们使用RSpec;在CI中,没有构建的资产,开发人员不想记住运行esbuild 或者assets:precompile或者其他什么东西。除了别的,它非常慢。
在基于Yarn/Node的工作流中,特别是使用cssbundling-railsjsbundling-rails的工作流中,当您想要使用最新的资产运行测试时,官方的惯用Rails 7解决方案是什么?

mm9b1k5b

mm9b1k5b1#

jsbundling-railscssbundling-rails都将自己附加到一个名为test:prepare的rake任务中。
有几种方法可以使test:prepare运行,具体取决于您的整个构建过程。
1.直接调用:
bundle exec rails test:prepare test
或者,如果在rails命令之外运行rspec:
bundle exec rails test:prepare && bundle exec rspec
1.使用已经调用test:prepare的测试任务。
奇怪的是,只有一些测试任务调用(依赖于)test:prepare,而其他任务(包括默认的test任务)不调用。
bundle exec rails test:all
1.使test:prepare成为您首选测试任务的依赖项。
例如,如果您通常通过运行bundle exec rails spec来使用spec任务,请将此添加到新的或现有的任务文件(如lib/tasks/tests.rake)中:
task spec: ['css:build', 'javascript:build']

背景

test:prepare是Rails定义的空任务。cssbundling-railsjsbundling-rails都将自己添加为该任务的依赖项。
一般来说,test:prepare是添加运行测试所需的任何类型的依赖项的有用位置,但需要注意的是,只有一些Rails的默认测试任务依赖于它。但如上所述,您始终可以直接调用它或添加自己的依赖项。
在大多数情况下,调用test:prepare将等同于调用css:buildjavascript:build,这就是为什么我在上面的大多数示例中展示了test:prepare。有时,其他gem或您的应用程序也可能使用附加命令扩展test:prepare,在这种情况下,这些命令也会运行(并且可能需要)。
还要注意,assets:precompile还依赖于css:buildjavascript:build。(或分别为css:buildjavascript:build)运行速度比assets:precompile快,这可能是因为我们运行的是sprockets-rails的轻量级配置(与propshaft相对),而assets:precompile运行整个编译过程。

mzaanser

mzaanser2#

这是相当糟糕的,但总比现在什么都没有好;它将确保CI始终构建资产,并确保本地开发始终拥有最新的资产,即使在bin/dev未运行时修改了内容。

# Under Rails 7 with 'cssbundling-rails' and/or the 'jsbundling-rails' gems,
# entirely external systems are used for asset management. With Sprockets no
# longer synchronously building assets on-demand and only when the source files
# changed, compiled assets might be (during local development) or will almost
# always be (CI systems) either out of date or missing when tests are run.
#
# People are used to "bundle exec rspec" and things working. The out-of-box gem
# 'cssbundling-rails' hooks into a vanilla Rails "prepare" task, running a full
# "css:build" task in response. This is quite slow and generates console spam
# on every test run, but points to a slightly better solution for RSpec.
#
# This class is a way of packaging that solution. The class wrapper is really
# just a namespace / container for the code.
#
# First, if you aren't already doing this, add the folllowing lines to
# "spec_helper.rb" somewhere *after* the "require 'rspec/rails'" line:
#
#     require 'rake'
#     YourAppName::Application.load_tasks
#
# ...and call MaintainTestAssets::maintain! (see that method's documentation
# for details). See also constants MaintainTestAssets::ASSET_SOURCE_FOLDERS and
# MaintainTestAssets::EXPECTED_ASSETS for things you may want to customise.
#
class MaintainTestAssets

  # All the places where you have asset files of any kind that you expect to be
  # dynamically compiled/transpiled/etc. via external tooling. The given arrays
  # are passed to "Rails.root.join..." to generate full pathnames.
  #
  # Folders are checked recursively. If any file timestamp therein is greater
  # than (newer than) any of EXPECTED_ASSETS, a rebuild is triggered.
  #
  ASSET_SOURCE_FOLDERS = [
    ['app', 'assets', 'stylesheets'],
    ['app', 'javascript'],
    ['vendor']
  ]

  # The leaf files that ASSET_SOURCE_FOLDERS will build. These are all checked
  # for in "File.join(Rails.root, 'app', 'assets', 'builds')". Where files are
  # written together - e.g. a ".js" and ".js.map" file - you only need to list
  # any one of the group of concurrently generated files.
  #
  # In a standard JS / CSS combination this would just be 'application.css' and
  # 'application.js', but more complex applications might have added or changed
  # entries in the "scripts" section of 'package.json'.
  #
  EXPECTED_ASSETS = %w{
    application.js
    application.css
  }

  # Call this method somewhere at test startup, e.g. in "spec_helper.rb" before
  # tests are actually run (just above "RSpec.configure..." works reasonably).
  #
  def self.maintain!
    run_build    = false
    newest_mtime = Time.now - 100.years

    # Find the newest modificaftion time across all source files of any type -
    # for simplicity, timestamps of JS vs CSS aren't considered
    #
    ASSET_SOURCE_FOLDERS.each do | relative_array |
      glob_path = Rails.root.join(*relative_array, '**', '*')

      Dir[glob_path].each do | filename |
        next if File.directory?(filename) # NOTE EARLY LOOP RESTART

        source_mtime = File.mtime(filename)
        newest_mtime = source_mtime if source_mtime > newest_mtime
      end
    end

    # Compile the built asset leaf names into full file names for convenience.
    #
    built_assets = EXPECTED_ASSETS.map do | leaf |
      Rails.root.join('app', 'assets', 'builds', leaf)
    end

    # If any of the source files are newer than expected built assets, or if
    # any of those assets are missing, trigger a rebuild task *and* force a new
    # timestamp on all output assets (just in case build script optimisations
    # result in a file being skipped as "already up to date", which would cause
    # the code here to otherwise keep trying to rebuild it on every run).
    #
    run_build = built_assets.any? do | filename |
      File.exist?(filename) == false || File.mtime(filename) < newest_mtime
    end

    if run_build
      Rake::Task['javascript:build'].invoke()
      Rake::Task[       'css:build'].invoke()

      built_assets.each { | filename | FileUtils.touch(filename, nocreate: true) }
    end
  end
end

字符串
(编辑)正如下面的评论者指出的,你需要确保Rake任务加载在你的spec_helper.rb中,例如:

require 'rake'
Rails.application.load_tasks

cwdobuhd

cwdobuhd3#

我最近在一个新的Rails7.1.2应用程序上使用RSpec时遇到了同样的困境。
在阅读了@tm上面写的很棒的答案之后,我运行rails -T为RSpec寻找类似的任务,并“发现”了这个:

bin/rails spec        # Run all specs in spec directory (excluding plugin specs)

字符串
它还调用test:prepare,如@tm所述。

相关问题