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?
The Railtie initializers are run through the run_initializers method which is defined in railties/lib/rails/initializable.rb: The run_initializers code itself is tricky. What Rails is doing here is traversing all the class ancestors looking for those that respond to an initializers method. It then sorts the ancestors by name, and runs them.
Rails::Railtie is the core of the Rails framework and provides several hooks to extend Rails and/or modify the initialization process. Every major component of Rails (Action Mailer, Action Controller, Active Record, etc.) implements a railtie.
This class includes a module called Initializable, which is actually Rails::Initializable. This module includes the initializer method which is used later on for setting up initializers, amongst other methods.
This makes Rails itself absent of any component hooks, allowing other components to be used in place of any of the Rails defaults. Developing a Rails extension does not require implementing a railtie, but if you need to interact with the Rails framework during or after boot, then a railtie is needed.
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).
In a before
or setup
block in your tests you can do something like this:
MyRailtie::Railtie.initializers.each(&:run)
MyEngine::Engine.initializers.each(&:run)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With