簡體   English   中英

如何通過rspec對靜態類方法進行存根

[英]How to stub static class methods through rspec

我有一個靜態方法,該方法通過進行外部服務調用來初始化靜態變量。 我想存根該靜態方法調用,以便在初始化類變量時不進行外部服務調用。 這是我的簡單代碼示例。

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

現在,我想用我的對象對靜態方法調用進行存根處理,以便使用要獲取的響應來初始化@@ 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中存根,盡管它將在執行到達那里的類變量初始化之前首先執行,但這也沒有幫助。 我現在堅持了一段時間。 有人請成為救世主。

我建議不要將“:ini”方法存根,我建議您將類變量@@ config設置為所需的值,因為我認為您無法執行該方法,因為解析器在調用該方法之前先通過ABC定義在您的before塊上:

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

然后嘗試看看這是否可以解決您的問題。

您的問題是,在加載類ABC會進行@@config的初始化,並且您無法通過存根干預該過程。 如果您不能對外部調用本身進行存根,那么我唯一想到的就是更改類定義以包括單獨的類初始化方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM