Introduce stub_env helper
ka8725 opened this issue · 1 comments
Stubbing environment variables is a common scenario when writing specs. RSpec does not have a built-in functionality for that. As a result, there are many solutions on the internet that seem quite complicated, often requiring the installation of additional gems. However, there is a very simple solution:
module Helpers
module StubEnvHelpers
def stub_env(name, val)
stub_const('ENV', ENV.to_hash.merge({name.to_s => val}))
end
end
end
RSpec.configure do |config|
config.include Helpers::StubEnvHelpers
end
# in spec:
before { stub_env(:MY_HOST, 'test.localhost') }I'm curious whether that doesn't raise any idiomatic concerns from the perspective of RSpec. Does it make sense to include it in RSpec-Core?
👋 We don't include it because its relatively simple to do for a specific use case, but there are a variety of ways to do it and a variety of knock on effects; In your case you are only stubbing one extra value, but what about multiple values, or removing existing values, or etc etc. You can also just use the ENV hash as is without stubbing at all quite happily.
Lastly, closing because this is the wrong repo, rspec-core constains no stubbing at all, thats rspec-mocks.