DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

11 3

RSpec & Rails: how to stub env vars

In order to stub an environment variable in the test (which is probably missing in test environment), stub :[] or fetch method:

# If code relies on ENV["CHARGES_TOKEN"]
allow(ENV)
  .to receive(:[])
  .with("CHARGES_TOKEN")
  .and_return("XXX")
Enter fullscreen mode Exit fullscreen mode
# If code relies on ENV.fetch("CHARGES_TOKEN")
allow(ENV)
  .to receive(:fetch)
  .with("CHARGES_TOKEN")
  .and_return("XXX")
Enter fullscreen mode Exit fullscreen mode

If you want shorter syntax, take a look at ClimateControl gem:

ClimateControl.modify CHARGES_TOKEN: "XXX" do
  # ...
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay