Search code examples
ruby-on-railsrubyrspecminitest

Is possible to test before Rails loaded?


I'm creating a gem and this gem depends Rails is loaded. I need to create a scenario when Rails is not loaded. I have this code in my gem as an example:

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

I've tried to create a stub, but it seems Rails restarts the application method when we set it with nil. https://github.com/rails/rails/blob/fbe2433be6e052a1acac63c7faf287c52ed3c5ba/railties/lib/rails.rb#L38

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

Solution

  • Easy. Just setup a bootstapper file for your test that does not load 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'
    

    In fact rspec-rails already generates two separate files*:

    • spec_helper.rb - just configures rspec.
    • rails_helper.rb requires spec_helper.rb and then boots Rails through require File.expand_path('../config/environment', __dir__).

    Simply changing require 'rails_helper' to require 'spec_helper' will change the test to become executed outside rails.

    However be aware that running the tests through Spring will generate strange results as it will keep Rails running in the background. If you're using a spring binstub you can disable spring with the DISABLE_SPRING env var.