How to trigger Railtie initializers in my tests?
Asked Answered
O

2

10

I have my own gem, and my railtie looks like...

class MyRailtie < Rails::Railtie
  initializer "my_railtie.configure_rails_initialization" do
    # some initialization behavior
  end
end

and I'm trying to test it, but in the tests the initializer never gets called. And I notice I have some dependences in another gems that have an initializer as well and they doesn't get called either.

Do you know what should I do besides require the file?

Overhasty answered 26/7, 2015 at 20:57 Comment(2)
Try Rails.application.initialize!Sarthe
Rails.application is nilImpeachable
A
8

Since initializers are part of Rails' functionality, you'll need to load that Railtie into a Rails application in order for it to be invoked automatically. This is usually done by building a small Rails app inside your spec folder, but that's a pain to set up by hand. Luckily, there's an excellent gem called combustion which makes testing engines (or gems with railties) a breeze. It will take care of setting up that Rails app for you, and ensure your tests run in that Rails environment (including running that initializer).

Agc answered 26/7, 2015 at 23:2 Comment(3)
Do we really need a dummy app? I've seen some gems doesn't need it, and still require rails.Impeachable
It depends what functionality of Rails your gem uses. Since you want to test the initializers, it's unfortunately pretty hard to run them in isolation -- the run_initializers method has undocumented arguments and likely expects a Rails application. Technically, you could figure all that out, but I think it'd be messier and more brittle than using combustion. You could also move the code in your initializer to a method, call that method from your tests, and just trust that the Railtie works as expected.Agc
I dig the Combustion gem! Very nice. Far less "scaffolding" for the "rails app" :) +1Massarelli
M
8

In a before or setup block in your tests you can do something like this:

For a Railtie

MyRailtie::Railtie.initializers.each(&:run)

For an Engine

MyEngine::Engine.initializers.each(&:run)
Maudemaudie answered 24/4, 2018 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.