Pistos
Pistos

Reputation: 23812

Run an rspec "before" block before rails initializers run

I would like to run an rspec before block to set some stuff up before the Rails initializers run, so I can test what an initializer should be doing. Is this possible?

Upvotes: 4

Views: 1761

Answers (1)

Winfield
Winfield

Reputation: 19145

If the logic in your initializers is complex enough it should be tested, you should extract it into a helper that you can isolate and test without being in the context of the initializer.

complex_initializer.rb

config.database.foo = calculate_hard_stuff()
config.database.bar = other_stuff()

You could extract that into a testable helper (lib/config/database.rb)

module Config::DatabaseHelper
  def self.generate_config
    {:foo => calculate_hard_stuff, :bar => other_stuff)
  end

  def calculate_hard_stuff
    # Hard stuff here
  end
end

...then just wire up the configuration data in your initializer

db_config_values = Config::DatabaseHelper.generate_config
config.database.foo = db_config_values[:foo]
config.database.bar = db_config_values[:bar]

...and test the complex configuration determination/calculation in a separate test where you can isolate the inputs.

describe Config::DatabaseHelper do
  describe '.calculate_hard_stuff' do
    SystemValue.stubs(:config => value)
    Config::DatabaseHelper.calculate_hard_stuff.should == expected_value
  end
end

Upvotes: 2

Related Questions