是否可以在加载Rails之前进行测试



我正在创建一个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的bootstapper文件。

# 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'

事实上,rspecrails已经生成了两个独立的文件*:

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

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

但是要注意,通过Spring运行测试会产生奇怪的结果,因为它会让Rails在后台运行。如果您使用的是弹簧binstub,您可以使用disable_spring env var.禁用弹簧

最新更新