可以在 Rails 加载之前进行测试吗?

Is possible to test before Rails loaded?

我正在创建一个 gem,这个 gem 取决于 Rails 是否已加载。我需要在未加载 Rails 时创建一个场景。我的 gem 中有此代码作为示例:

if defined?(Rails) && Rails.application
 #some code
end

我试图创建一个存根,但当我们将其设置为 nil 时,似乎 Rails 重新启动了应用程序方法。 https://github.com/rails/rails/blob/fbe2433be6e052a1acac63c7faf287c52ed3c5ba/railties/lib/rails.rb#L38

Rails.stub(:application, nil) do
 # test
end

简单。只需为您的测试设置一个不加载 Rails.

的引导程序文件
# spec/barebones_helper.rb
RSpec.configure do |config|

end

# optionally load your dependencies:
# Bundler.require(:some_group)
# spec/lib/mygem_spec.rb
require 'barebones_helper'

事实上rspec-rails已经生成了两个单独的文件*:

  • spec_helper.rb - 只需配置 rspec.
  • rails_helper.rb 需要 spec_helper.rb 然后通过 require File.expand_path('../config/environment', __dir__).
  • 启动 Rails

只需将 require 'rails_helper' 更改为 require 'spec_helper' 即可将测试更改为在 rails 之外执行。

但是请注意,通过 Spring 进行的 运行 测试会产生奇怪的结果,因为它会在后台保留 Rails 运行。如果您使用的是 spring binstub,您可以使用 DISABLE_SPRING env var.

禁用 spring