暂时覆盖Rails测试中的配置

时间:2014-12-02 10:37:49

标签: ruby-on-rails ruby testing

我需要测试一些Rails代码,但在测试期间我想覆盖一些配置选项。

使用Python背景,我会这样做:

def test():
    # ...
    with change_config(key, new_value):
       # do stuff with config changed
    # config is back to old value

我如何在Rails / Ruby中实现这一目标?

3 个答案:

答案 0 :(得分:0)

这有用吗?

def test
  Rails.config.action_mailer.delivery_method = :test
end

答案 1 :(得分:0)

我不是红宝石专家,但这就是我想出的。也许有一种更惯用的方式来编写它,但是它对我来说仍然有效。

包装要执行的代码块,并覆盖设置,保存原始值,并在该块完成执行后将其恢复。

# in `test_helper.rb`
def stub_dev_s3_setting(value, &block)
  original_value = Settings.aws.s3.use_s3_in_dev
  Settings.aws.s3.use_s3_in_dev = value
  block.call
ensure
  Settings.aws.s3.use_s3_in_dev = original_value
end

在单元测试中使用:

it 'overrides setting in dev to use s3' do
  stub_dev_s3_setting true do
    # do stuff with AWS S3 and assert that it worked as expected...
    # when this block of code exits, the original value of the setting
    # will be restored automatically
  end
end

答案 2 :(得分:0)

在测试中临时启用配置值:

before { Rails.configuration.action_mailer.raise_delivery_errors = true }
after { Rails.configuration.action_mailer.raise_delivery_errors = false }