在测试过程中把ENV改成 "生产",可能会有什么不良后果?

问题描述 投票:0回答:1

我写了一段代码,只需要在生产环境下运行。在我的spectest文件中,当测试这段代码时,我必须将ENV变量改为 "生产",这样代码才能正常运行。

这段代码是这样的。

do_something if Rails.env.production?

Spec:

context "some context" do

  before { Rails.env = 'production' }

  # test something

end

我的问题是: 这种方法有问题吗?另一个选择是将代码改为在 "生产 "或 "测试 "环境下运行。这在某种程度上是否 "更好"?我觉得我不应该在测试过程中改变环境,但不知道这样做是否正确,为什么。

ruby-on-rails ruby testing rspec
1个回答
0
投票

与其在测试过程中改变环境,不如创建一个ActiveSupport:StringInquirer(Rails.env的类)的实例,然后用它来代替。

 class MyClassThatNeedsEnvironment
     def initialize(env)
       @env = env
     end

     def foo
       do_something if @env.production?
     end
 end

Test Example:

    context "test" do

    let(:my_class_instance) {
        env_as_string = Rails.env.to_s    
MyClassThatNeedsEnvironment.new(ActiveSupport::StringInquirer.new(env_as_string))

    }

    end

    context "production" do
      let(:my_class_instance) {
        env_as_string = 'production'   

    MyClassThatNeedsEnvironment.new(ActiveSupport::StringInquirer.new(env_as_string))

    }
    end

这样做没有副作用,而且保留了依赖性反转。

© www.soinside.com 2019 - 2024. All rights reserved.