9

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?

Steven Barragán
  • 1,144
  • 1
  • 11
  • 21

2 Answers2

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

Robert Nubel
  • 7,104
  • 1
  • 18
  • 30
  • Do we really need a dummy app? I've seen some gems doesn't need it, and still require rails. – Steven Barragán Jul 27 '15 at 16:37
  • 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](http://api.rubyonrails.org/classes/Rails/Initializable.html#method-i-run_initializers) 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. – Robert Nubel Jul 27 '15 at 17:10
  • I dig the Combustion gem! Very nice. Far less "scaffolding" for the "rails app" :) +1 – Volte Nov 29 '17 at 00:02
6

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)
Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104