rspec / rspec-core

RSpec runner and formatters
http://rspec.info
MIT License
1.23k stars 765 forks source link

Introduce stub_env helper #3044

Closed ka8725 closed 1 year ago

ka8725 commented 1 year ago

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?

JonRowe commented 1 year ago

:wave: 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.