A long-lived project that still receives updates
Stub or hide environment variables in a scoped context for testing stub_env('REDIS_URL' => 'redis://localhost:6379/') hide_env('SESSION_SECRET')
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

 Project Readme

RSpec::StubbedEnv

Version License: MIT Downloads Rank Open Source Helpers Depfu CodeCov Test Coverage Coveralls Test Coverage CodeClimate Test Coverage Maintainability CI Heads CI Current CI Truffle Ruby CI JRuby CI Supported CI Legacy CI Unsupported CI Ancient CI Test Coverage CI Style


Liberapay Patrons Sponsor Me on Github Buy me a coffee Donate on Polar Donate to my FLOSS or refugee efforts at ko-fi.com Donate to my FLOSS or refugee efforts using Patreon

  • ENV stubbing and hiding via shared contexts for more powerful tests
  • Now you don't need to add dotenv just for your spec suite
  • ENV hiding via hide_env("FOO") was added in v1.0.2
describe "my stubbed test" do
  include_context "with stubbed env"
  include_context "with hidden env"
  context "with FOO=is bar" do
    before do
      stub_env("FOO" => "is bar")
    end
    it "has a value" do
      expect(ENV.fetch("FOO", nil)).to(eq("is bar"))
      expect(ENV.fetch("FOO")).to(eq("is bar"))
      expect(ENV["FOO"]).to(eq("is bar"))
    end
  end
  context "without BAR set" do
    before do
      hide_env("BAR")
    end
    it "is nil" do
      expect(ENV.fetch("BAR", nil)).to(be_nil)
      expect(ENV["BAR"]).to(be_nil)
    end
    it "raises error" do
      expect { ENV.fetch("BAR") }.to(raise_error(KeyNotFound))
    end
  end
end

This gem has no runtime dependencies.

๐Ÿ’ก Info you can shake a stick at

Tokens to Remember Gem name Gem namespace
Works with JRuby JRuby 9.1 Compat JRuby 9.2 Compat JRuby 9.3 Compat JRuby 9.4 Compat JRuby 10.0 Compat JRuby HEAD Compat
Works with Truffle Ruby Truffle Ruby 22.3 Compat Truffle Ruby 23.0 Compat Truffle Ruby 23.1 Compat Truffle Ruby 24.1 Compat Truffle Ruby HEAD Compat
Works with MRI Ruby 3 Ruby 3.0 Compat Ruby 3.1 Compat Ruby 3.2 Compat Ruby 3.3 Compat Ruby 3.4 Compat Ruby HEAD Compat
Works with MRI Ruby 2 Ruby 2.3 Compat Ruby 2.4 Compat Ruby 2.5 Compat Ruby 2.6 Compat Ruby 2.7 Compat
Source Source on GitLab.com Source on CodeBerg.org Source on Github.com The best SHA: dQw4w9WgXcQ!
Documentation Current release on RubyDoc.info HEAD on RubyDoc.info BDFL Blog Wiki
Compliance License: MIT ๐Ÿ“„ilo-declaration-img Security Policy Enforced Code Style CodeQL Contributor Covenant 2.1 SemVer 2.0.0 Keep-A-Changelog 1.0.0 Gitmoji Commits
Expert 1:1 Support Get help from me on Upwork or Get help from me on Codementor
Enterprise Support Get help from me on Tidelift
๐Ÿ’กSubscribe for support guarantees covering all FLOSS dependencies!
๐Ÿ’กTidelift is part of Sonar!
๐Ÿ’กTidelift pays maintainers to maintain the software you depend on!
๐Ÿ“Š@Pointy Haired Boss: An enterprise support subscription is "never gonna let you down", and supports open source maintainers!
Comrade BDFL ๐ŸŽ–๏ธ Follow Me on LinkedIn Follow Me on Ruby.Social Follow Me on Bluesky Contact BDFL My technical writing
... ๐Ÿ’– Find Me on WellFound: Find Me on CrunchBase My LinkTree More About Me ๐ŸงŠ ๐Ÿ™ ๐Ÿ›– ๐Ÿงช

โœจ Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add rspec-stubbed_env

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install rspec-stubbed_env

๐Ÿ”’ Secure Installation

rspec-stubbed_env is cryptographically signed, and has verifiable SHA-256 and SHA-512 checksums by stone_checksums. Be sure the gem you install hasnโ€™t been tampered with by following the instructions below.

Add my public key (if you havenโ€™t already, expires 2045-04-29) as a trusted certificate:

gem cert --add <(curl -Ls https://raw.github.com/oauth-xx/rspec-stubbed_env/main/certs/pboling.pem)

You only need to do that once. Then proceed to install with:

gem install rspec-stubbed_env -P HighSecurity

The HighSecurity trust profile will verify signed gems, and not allow the installation of unsigned dependencies.

If you want to up your security game full-time:

bundle config set --global trust-policy MediumSecurity

MediumSecurity instead of HighSecurity is necessary if not all the gems you use are signed.

NOTE: Be prepared to track down certs for signed gems and add them the same way you added mine.

๐Ÿ”ง Basic Usage

You must configure RSpec to use the :expect syntax, or some compatible alternative.

RSpec.configure do |config|
  config.expect_with(:rspec) do |c|
    c.syntax = :expect
  end
end

Require the library in your spec/test helper somewhere:

require "rspec/stubbed_env"

ENV stubbing

  • is opt-in, via a shared context, rather than global.
  • does not affect the real ENV at all. It is a true stub.
  • has the same scope as a before, subject, or let at the same level.

See the spec suite for detailed examples.

# This is normal, without stubbing, ENV is not set
describe "vanilla" do
  it "has no ENV stub" do
    expect(ENV.fetch("FOO", nil)).to(be_nil)
    expect(ENV["FOO"]).to(be_nil)
  end
end

# With a stubbed ENV!
describe "my stubbed test" do
  include_context "with stubbed env"
  before do
    stub_env("FOO" => "is bar")
  end
  it "has a value" do
    expect(ENV.fetch("FOO", nil)).to(eq("is bar"))
    expect(ENV["FOO"]).to(eq("is bar"))
  end
end

ENV can be stubbed trough the stub_env method, or key/value pairs to be stubbed can be provided directly to the include_context call:

describe "my stubbed test" do
  include_context "with stubbed env", "FOO" => "is bar"

  it "has a value" do
    expect(ENV.fetch("FOO", nil)).to(eq("is bar"))
    expect(ENV["FOO"]).to(eq("is bar"))
  end
end

If you want to make stub_env method available globally (without the include_context call), you can add in the spec_helper.

I do not recommend the global approach, as it results in a loss of clarity on which tests are testing ENV-based behaviors. Here's a foot-gun if you want it.

RSpec.configure do |config|
  config.include(RSpec::StubbedEnv::StubHelpers)
  # Or you could include the context globally
  # config.include_context "with stubbed env"
end

ENV hiding

  • is opt-in, via a shared context, rather than global.
  • does not affect the real ENV at all. It is a true stub.
  • has the same scope as a before, subject, or let at the same level.

See the spec suite for detailed examples.

# This is normal, without hiding, ENV is set
ENV["MY_PATH"] = "/home/doodle"
describe "vanilla" do
  it "has ENV with nothing hidden" do
    expect(ENV.fetch("MY_PATH", nil)).to("/home/doodle")
    expect(ENV["MY_PATH"]).to("/home/doodle")
  end
end

# With a hidden ENV variable!
describe "my hidden test" do
  include_context "with hidden env"
  before do
    hide_env("MY_PATH")
  end
  it "MY_PATH is not set" do
    expect(ENV.fetch("MY_PATH", nil)).to(be_nil)
    expect(ENV["MY_PATH"]).to(be_nil)
  end
end

ENV variables can be hidden trough the hide_env method, or variable names to be hidden can be provided directly to the include_context call:

describe "my hidden test" do
  include_context "with hidden env", "MY_PATH"

  it "MY_PATH is not set" do
    expect(ENV.fetch("MY_PATH", nil)).to(be_nil)
    expect(ENV["MY_PATH"]).to(be_nil)
  end
end

If you want to make hide_env method available globally (without the include_context call), you can add in the spec_helper:

I do not recommend the global approach, as it results in a loss of clarity on which tests are testing ENV-based behaviors. Here's a foot-gun if you want it.

RSpec.configure do |config|
  config.include(RSpec::StubbedEnv::HideHelpers)
  # Or you could include the context globally
  # config.include_context "with hidden env"
end

๐Ÿšš Switch to main branch

We migrated from master to main as the default branch. If this affected your local checkout:

git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a

๐Ÿš€ Release Instructions

See CONTRIBUTING.md.

๐Ÿ” Security

See SECURITY.md.

๐Ÿค Contributing

If you need some ideas of where to help, you could work on adding more code coverage, or if it is already ๐Ÿ’ฏ (see below) check TODOs (see below), or check issues, or PRs, or use the gem and think about how it could be better.

We Keep A Changelog so if you make changes, remember to update it.

See CONTRIBUTING.md for more detailed instructions.

Code Coverage

Coverage Graph

๐Ÿช‡ Code of Conduct

Everyone interacting in this project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the Contributor Covenant 2.1.

๐ŸŒˆ Contributors

Contributors

Made with contributors-img.

Also see GitLab Contributors: https://gitlab.com/pboling/rspec-stubbed_env/-/graphs/main

โญ๏ธ Star History

Star History Chart

๐Ÿ“Œ Versioning

This Library adheres to Semantic Versioning 2.0.0. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions.

๐Ÿ“Œ Is "Platform Support" part of the public API?

Yes. But I'm obligated to include notes...

SemVer should, but doesn't explicitly, say that dropping support for specific Platforms is a breaking change to an API. It is obvious to many, but not all, and since the spec is silent, the bike shedding is endless.

dropping support for a platform is both obviously and objectively a breaking change

To get a better understanding of how SemVer is intended to work over a project's lifetime, read this article from the creator of SemVer:

As a result of this policy, and the interpretive lens used by the maintainer, you can (and should) specify a dependency on these libraries using the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency("rspec-stubbed_env", "~> 1.0")

See CHANGELOG.md for list of releases.

๐Ÿ“„ License

The gem is available as open source under the terms of the MIT License License: MIT. See LICENSE.txt for the official Copyright Notice.

ยฉ Copyright

Copyright (c) 2018 - 2020, 2024 - 2025 Peter H. Boling, RailsBling.com Rails Bling

๐Ÿค‘ One more thing

You made it to the bottom of the page, so perhaps you'll indulge me for another 20 seconds. I maintain many dozens of gems, including this one, because I want Ruby to be a great place for people to solve problems, big and small. Please consider supporting my efforts via the giant yellow link below, or one of the others at the head of this README.

Buy me a latte