简体   繁体   English

如何通过rspec对静态类方法进行存根

[英]How to stub static class methods through rspec

I have a static method which initiates a static variable by making a external service call. 我有一个静态方法,该方法通过进行外部服务调用来初始化静态变量。 I want to stub that static method call so that external service call is not made while initializing of the class variable. 我想存根该静态方法调用,以便在初始化类变量时不进行外部服务调用。 here is an example of my code in simple terms. 这是我的简单代码示例。

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

Now I want to stub the static method call with my object so that @@config is initialized with the response which I want to get. 现在,我想用我的对象对静态方法调用进行存根处理,以便使用要获取的响应来初始化@@ config。 I have tried several things and I seems that @@config is not initialized with my object but by the implemented call only. 我已经尝试了几件事,并且似乎@@ 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

I have even tried stubing in the spec_helper with the though that it will be executed first before the class variable is initialized when execution reaches there, but that also did not help. 我什至尝试在spec_helper中存根,尽管它将在执行到达那里的类变量初始化之前首先执行,但这也没有帮助。 I am stuck with this now for a while. 我现在坚持了一段时间。 Someone please be a Savior. 有人请成为救世主。

Instead of stubbing the ":ini" method, which I suppose that you cannot do because the parser goes through the ABC definition before your call to stub the method, I would suggest that you set the class variable @@config to the value you want on your before block: 我建议不要将“:ini”方法存根,我建议您将类变量@@ config设置为所需的值,因为我认为您无法执行该方法,因为解析器在调用该方法之前先通过ABC定义在您的before块上:

before(:each) do
  ABC.class_variable_set(:@@config, myObject)
end

Then try to see whether this solves your problem. 然后尝试看看这是否可以解决您的问题。

Your problem is that the initialization of @@config is occurring while the class ABC is being loaded and there is no way for you intervene in that process via stubbing. 您的问题是,在加载类ABC会进行@@config的初始化,并且您无法通过存根干预该过程。 If you cannot stub the external call itself, then the only thing I can think of is to change the class definition to include a separate class initialization method. 如果您不能对外部调用本身进行存根,那么我唯一想到的就是更改类定义以包括单独的类初始化方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM