ruby-on-rails - 在 rails 初始化程序运行之前运行 rspec "before" block

标签 ruby-on-rails ruby rspec initializer

我想运行一个 rspec before block 来在 Rails 初始化器运行之前设置一些东西,这样我就可以测试初始化​​器应该做什么。这可能吗?

最佳答案

如果您的初始化程序中的逻辑足够复杂,则应该对其进行测试,您应该将其提取到一个帮助程序中,您可以在不处于初始化程序上下文的情况下隔离和测试它。

complex_initializer.rb

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

您可以将其提取到可测试的帮助程序 (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

...然后只需在初始化程序中连接配置数据

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

...并在单独的测试中测试复杂的配置确定/计算,您可以在其中隔离输入。

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

关于ruby-on-rails - 在 rails 初始化程序运行之前运行 rspec "before" block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557636/

相关文章:

ruby-on-rails - 将日期与 rails3 中的日期时间 Created_at 进行比较

Ruby:将记录器消息发送到字符串变量?

ruby-on-rails - 更改 form_for 中标签上的文本

ruby - 使用 Nokogiri 时,如何抑制自关闭标签的插入?

ruby-on-rails - 如何在 RSpec 中包含多个模块?

ruby-on-rails - Controller Spec#Show Action : exoected: [Object], 得到:无错误 - RSpec 3

ruby-on-rails - 如何在 ActiveRecord 中编写集合操作查询而不在 SQL 中编写 INTERSECT、UNION 或 EXCEPT?

ruby-on-rails - rails : Having problems with follow and followed system

ruby-on-rails - 使用范围来过滤 Rails 5 中的结果

mysql - OpsWorks 已部署,但我的所有操作均无效。我的 database.yml 文件搞砸了吗?