我有一个静态方法,它通过进行外部服务调用来启动静态变量。我想 stub 该静态方法调用,以便在初始化类变量时不会进行外部服务调用。 这是我的代码的简单示例。
class ABC
def self.ini
return someCallToMyExternalLibrary # i don't want the execution to go there while testing
end
@@config = self.ini
def method1
return @@config['download_URL']
end
end
现在我想用我的对象对静态方法调用进行 stub ,以便使用我想要获得的响应来初始化@@config。 我已经尝试了几件事,我似乎 @@config 不是用我的对象初始化的,而是仅由实现的调用初始化的。
describe ABC do
let(:myObject) { Util.jsonFromFile("/data/app_config.json")}
let(:ABC_instance) { ABC.new }
before(:each) do
ABC.stub(:ini).and_return(myObject)
end
it "check the download url" do
ABC_instance.method1.should eql("download_url_test")
# this test fails as @@config is not getting initialized with my object
# it returns the download url as per the implementation.
end
end
我什至尝试在spec_helper中 stub ,尽管当执行到达那里时,它将在类变量初始化之前首先执行,但这也没有帮助。我现在被这个问题困扰了一段时间。请有人成为救世主。
最佳答案
您的问题是,@@config
的初始化是在加载类 ABC
时发生的,并且您无法通过 stub 干预该过程。如果您无法对外部调用本身进行 stub ,那么我唯一能想到的就是更改类定义以包含单独的类初始化方法。
关于ruby-on-rails - 如何通过 rspec stub 静态类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073662/