RSpec & Rails: how to stub env vars

vasily

Vasily Polovnyov

Posted on May 17, 2022

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
đź’– đź’Ş đź™… đźš©
vasily
Vasily Polovnyov

Posted on May 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related