Run an rspec “before” block before rails initializers run

风格不统一 提交于 2019-12-10 17:26:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!