RSpec & Rails: how to stub env vars
Vasily Polovnyov
Posted on May 17, 2022
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")
# If code relies on ENV.fetch("CHARGES_TOKEN")
allow(ENV)
.to receive(:fetch)
.with("CHARGES_TOKEN")
.and_return("XXX")
If you want shorter syntax, take a look at ClimateControl gem:
ClimateControl.modify CHARGES_TOKEN: "XXX" do
# ...
end
đź’– đź’Ş đź™… đźš©
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.