运行 rspec “before"在 rails 初始化程序运行之前阻止 [英] Run an rspec "before" block before rails initializers run

查看:40
本文介绍了运行 rspec “before"在 rails 初始化程序运行之前阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个 rspec before 块来设置一些东西before Rails 初始化程序运行,这样我就可以测试初始化​​程序应该做什么.这可能吗?

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

complex_initializer.rb

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

您可以将其提取到可测试的帮助程序 (lib/config/database.rb) 中

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

这篇关于运行 rspec “before"在 rails 初始化程序运行之前阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆