问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/7557636/run-an-rspec-before-block-before-rails-initializers-run