Properly mocking environment variables with minitest?

huangapple go评论96阅读模式
英文:

Properly mocking environment variables with minitest?

问题

什么是在使用 minitest 进行 Ruby on Rails 单元测试时模拟环境变量的正确方法?

所以我来自Python,标准方式是使用装饰器,就像这样:

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

当我在文档和Stack Overflow搜索时,很惊讶地发现在 minitest 中找不到类似的内容。

对于如何最好地处理这个问题的任何建议将不胜感激!

英文:

What's the right way to mock environment variables when writing unit tests using minitest for Ruby on Rails?

So I'm coming from Python where the standard way is to use a decorator like this:

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

I'm a little surprised I've been unable to find anything similar in minitest when searching the documentation and Stack Overflow.

Any recommendations for the best approach to do this would be much appreciated!

答案1

得分: 2

你可以使用以下方法设置和取消设置环境变量,例如:

# 在 test_helper.rb 中(例如)
def mock_env(partial_env_hash)
  old = ENV.to_hash
  ENV.update partial_env_hash
  begin
    yield
  ensure
    ENV.replace old
  end
end

# 用法
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的文章,详细介绍了如何在测试期间设置和取消设置环境变量的更多选项,如果你想了解更多。

英文:

You can set and unset environment variables using a method, for example:

# 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

You can alternatively use the climate_control gem to manage environment variables:

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

There's also a decent article called How environment variables make your Ruby test suite flaky that goes into some more detail about how to set and unset environment variables during tests if you'd like to read about some more options.

huangapple
  • 本文由 发表于 2023年4月17日 22:56:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定