ruby 使用minitest正确模拟环境变量?

hmtdttj4  于 2023-04-20  发布在  Ruby
关注(0)|答案(1)|浏览(94)

在使用Ruby on Rails的minitest编写单元测试时,模拟环境变量的正确方法是什么?
所以我从Python开始,标准的方法是使用这样的装饰器:

@mock.patch.dict(os.environ, {'mocked_key': 'mocked_result'}

我有点惊讶,在搜索文档和Stack Overflow时,我无法在minitest中找到任何类似的东西。
任何建议的最佳方法来做到这一点将不胜感激!

42fyovps

42fyovps1#

您可以set and unset environment variables using a method,例如:

# in test_helper.rb (for example)
def mock_env(partial_env_hash)
  old = ENV.to_hash
  ENV.update partial_env_hash
  begin
    yield
  ensure
    ENV.replace old
  end
end

# usage
mock_env('MY_ENV_VAR' => 'Hello') do
  assert something?
end

您也可以使用climate_control gem来管理环境变量:

ClimateControl.modify CONFIRMATION_INSTRUCTIONS_BCC: 'confirmation_bcc@example.com' do
  sign_up_as 'john@example.com'

  confirm_account_for_email 'john@example.com'

  expect(current_email).to bcc_to('confirmation_bcc@example.com')
end

还有一篇名为How environment variables make your Ruby test suite flaky的文章,如果你想了解更多的选项,它更详细地介绍了如何在测试期间设置和取消设置环境变量。

相关问题