【问题标题】:Run tests located in a Rails Engine when mounted in host application安装在主机应用程序中时运行位于 Rails 引擎中的测试
【发布时间】:2022-07-16 16:39:23
【问题描述】:

我在名为“Blorgh”的引擎中进行了一些测试。我只是通过在我的引擎存储库的根目录中运行以下命令来测试我的引擎。

rails test
...
19 runs, 8 assertions, 0 failures, 0 errors, 11 skips

简单。现在,Blorgh 已安装在应用程序中。

gem blorgh

此应用是使用包含测试步骤的管道部署的。我希望测试步骤执行已安装引擎的测试,以便管道在发现 Blorgh 引擎中的测试存在问题时停止部署。

问题是当rails test在宿主应用的根目录下执行时,它只查找宿主应用特定的测试。

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

如何在 Blorgh 引擎安装后对其执行测试?我搜索了高低。我愿意通过爬取Blorgh::Engine.root 来完成我自己的任务,但我什至不确定rails test 在幕后做了什么。

【问题讨论】:

  • 我认为您在与为什么使用引擎的本质作斗争,即将引擎的开发与应用程序隔离开来。如果您在引擎中使用某种版本控制并且该应用程序需要其 gemfile 中的特定版本,我看不出您为什么实际需要它。
  • 这不能代替单独测试引擎。而引擎有自己的管道和测试步骤;这不会主动阻止开发人员意外指向损坏的引擎版本并自动部署该损坏的引擎。我正在使用的管道无法咨询另一个管道的构建状态。至少不是没有拼凑出一个黑客解决方案。
  • 说我安装了devise,我不想运行它的测试,但我想确保我的身份验证正常工作并且我的“/users/sign_in”页面正常工作,我会不要依赖引擎,我会在我的主应用程序中编写自己的测试。如果主应用程序没有测试引擎提供的功能,您的引擎可以像任何其他 gem 一样制动您的应用程序。语义版本控制、重大更改以及所有这些都是缓解此问题的确切工具。如果引擎与主应用程序紧密耦合,只需像 rails 一样保持版本同步。

标签: ruby-on-rails unit-testing rails-engines ruby-on-rails-6.1


【解决方案1】:

您可以设置 rake 任务以仅加载必要的测试。主应用程序 test 目录应该在您的加载路径中,因为 test/test_helper.rb 会加载环境:

# lib/tasks/run_engine_tests.rake

task :run_engine_tests do
  # NOTE: Add main app `test` directory to load path.
  #       This makes requires such as `require "test_helper"`
  #       load main app helper instead of engine helper.
  #       That's what we need to run the tests under our app,
  #       because engine's `test_helper.rb` loads dummy app.
  $LOAD_PATH << Rails.root.join("test").to_s

  # NOTE: Require tests from the engine that you need to run.
  Dir.glob(Blorgh::Engine.root.join("test/**/*_test.rb")).each { |f| require f }
  
  # NOTE: Rails magic does the rest. 
  #       Well, it only executes `Minitest.autorun`
  require "active_support/testing/autorun"
end

快速测试:

$ RAILS_ENV=test bin/rails run_engine_tests
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 12153

# Running:

hello from Blorgh
.

Finished in 0.004990s, 200.4139 runs/s, 200.4139 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

使用RAILS_ENV=test,否则会加载两次测试环境,导致fixture也加载两次。


https://github.com/rails/rails/blob/v7.0.2.3/railties/lib/rails/commands/test/test_command.rb#L29

https://github.com/rails/rails/blob/v7.0.2.3/railties/lib/rails/test_unit/runner.rb#L39

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多