如何在 rspec 中测试由 Settings.production 确定的环境?

How to test, in rspec, environment determined with Settings.production?

我在 Sinatra 项目中有一个逻辑,它根据环境是生产环境还是开发环境来确定不同的行为。

if Services.production?
    # do something
else
    # do something else
end

我如何测试这段代码?我尝试了以下但没有用:

expect_any_instance_of(Services).to receive(:production?).and_return(true)

它不是您调用 production?Services 实例,它是 Services class 本身。你应该可以做到

expect(Services).to receive(:production?).and_return(true)

从你的代码来看,它看起来像生产?是一个 class 方法,因此它不是在服务实例上调用,而是在 class 服务上调用。 尝试

expect(Services).to receive(:production?).and_return(true)