运行 rspec for ruby​​ 时如何更改环境变量? [英] how can I change environment variables when running rspec for ruby?

查看:25
本文介绍了运行 rspec for ruby​​ 时如何更改环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 ruby​​ 脚本并使用 rspec 测试它们.

I have several ruby scripts and test them with rspec.

我将我的环境放在 env.rb 文件中(暂时),以便我可以在本地访问它们,并在生产中将它们放在配置变量中.

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

但是当我运行 rspec 时,我想要不同的环境变量.两个用例:

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

  • 我运行 Twilio,所以我希望能够更改用于其测试凭据的 SID
  • 我将内容作为服务存储在数据库中,并希望拥有一个单独的测试数据库

推荐答案

你可以

  • 在上下文中使用 ENV["FOO_BAR"] = "baz"
  • 显式设置 ENV 变量
  • 在初始化程序中检查 Rails.env.test? 以使用特定于测试的选项设置 twilio 和其他客户端
  • 有一个包含所有环境设置的文件用于测试,然后使用 dotenv
  • set ENV vars explicitly in the context with ENV["FOO_BAR"] = "baz"
  • check Rails.env.test? in your initializers to setup twilio and other clients with test specific opts
  • have a file with all your env setup for test and then use dotenv

我个人更喜欢只在创建对象然后将 env var 值传递给构造函数时才使用 ENV 变量,这样我就可以测试对象类而不用关心 ENV,并且我可以测试初始化​​另一个对象的对象env var,通过断言创建使用了 env var.

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

所以你会改变一些东西

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

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

并初始化该实例然后传递env var的值

and have whatever is initializing that instance to then pass the value of the env var

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

这样你就可以测试 Client 类,而无需关心 env var,只需传递任何 url,然后就可以测试实例化 client 的类为

this way you can test the Client class without caring about the env var by just passing any url, and then can test the class that instantiates 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

更新 env var 的一个问题是更改在测试套件的其余部分持续存在,如果您不希望它在某些测试中出现,则可能会导致问题,在这些情况下,您可以模拟该值

one problem with updating the env var is that the change persist throughout the rest of the test suite, and may cause problems if you don't expect it to be there in some tests, in these cases you can mock the value with

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

这篇关于运行 rspec for ruby​​ 时如何更改环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆