How to change environment variables when starting rspec for ruby?

I have some ruby ​​scripts and test them with rspec.

I put my environments in the env.rb file (for now), so I can access them locally and put them in configuration variables during production.

But when I run rspec, I need different environment variables. Two use cases:

  • I am running Twilio, so I want to be able to change the SID used for their test credentials.
  • I store things in the database as a service and want to have a separate test database
+5
source share
1 answer

You can

  • set ENV vars values ​​explicitly in the context of ENV["FOO_BAR"] = "baz"
  • check out Rails.env.test? in your initializers to configure twilio and other clients with specific selection criteria.
  • you have a file with your entire env installation for testing, and then use dotenv

I personally prefer to use ENV vars only when creating objects, and then passing the env var value to the constructor, so I can check the class of the object without worrying about ENV, and I can check the object that initializes another object with env var, just asserting the creation, used by env var.

So you change something like

 class Client def initialize @restclient = RestClient::Resource.new(ENV["API_URL"]) end end 

to

 class Client def initialize(url) @restclient = RestClient::Resource.new(url) end end 

and all that initializes this instance, then pass the value env var

 def fetch_content client = Client.new(ENV["API_URL"]) # ... end 

this way you can test the Client class without worrying about env var, just passing any URL, and then you can test the class creating the Client as

 it "uses client" do ENV["API_URL"] = "foo.com" expect(Client).to receive(:new).with(ENV["API_URL"]) subject.fetch_content end 

one problem with updating env var is that the change is saved in the rest of the test suite and can cause problems if you do not expect it to be present in some tests, in which cases you can make fun of this value with

 expect(ENV).to receive(:[]).with("API_URL").and_return("foo.com") 
+2
source

Source: https://habr.com/ru/post/1209515/


All Articles