Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce stub_env helper #3044

Closed
ka8725 opened this issue Jul 4, 2023 · 1 comment
Closed

Introduce stub_env helper #3044

ka8725 opened this issue Jul 4, 2023 · 1 comment

Comments

@ka8725
Copy link

ka8725 commented Jul 4, 2023

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
Copy link
Member

JonRowe commented Jul 4, 2023

👋 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.

@JonRowe JonRowe closed this as completed Jul 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants