DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

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

Discussion (0)