开发者

Run an rspec "before" block before rails initializers run

开发者 https://www.devze.com 2023-04-07 10:21 出处:网络
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?If the logic in your

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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号