Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Railtie initializers in my tests?

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?

like image 818
Steven Barragán Avatar asked Jul 26 '15 20:07

Steven Barragán


People also ask

How do I run the railtie initializers?

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.

What is railtie in rails?

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.

What is the use of initializable class in rails?

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.

Do I need a railtie for a rails extension?

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.


2 Answers

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).

like image 62
Robert Nubel Avatar answered Sep 23 '22 19:09

Robert Nubel


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)
like image 35
Ryan McGeary Avatar answered Sep 23 '22 19:09

Ryan McGeary