2014-09-22 43 views
0

我有一個項目現在使用RSpec 3,但仍包含(現在不推薦使用)用於存根方法的RSpec 2語法。Rails/rspec方法翻倍而不是any_instance.stub

目前我們廣泛使用:

Class::OtherClass.any_instance.stub(:method) 

這些是從包含在ActiveRecord模型(這是第二重要的)仿真模塊調用。

模擬中的方法根據應用程序是否應該爲真實或模擬模式運行其規格來從規範內調用。

因此,仿真模塊最終看起來是這樣的:

module Foo::Simulation 
    def break_baz! 
    Foo::Bar.any_instance.stub(:baz).and_raise(ArgumentError.new("You broke your baz!")) 
    end 
end 

我試圖將它轉換爲用雙打,但我想不出雙打等效語法。

任何人都可以用複製any_instance.stub行爲的方式幫我解決雙打問題嗎?

編輯1

我已經走了這麼遠最接近:

module Foo::Simulation 
    def break_baz! 
    allow(self.baz).to receive(ArgumentError.new("You broke your baz!")) 
    end 
end 

但是當對象ID的變化,當我發佈到一個控制器,該方法不再存根。

編輯2

這是儘可能多的代碼,我可以提供:

class Provider 
    include Provider::Simulation 

    def iam 
    Fog::AWS::IAM.new(credentials) 
    end 
end 

然後,仿真:

module Provider::Simulation 
    def break_server_certificates! 
    Fog::Mock.any_instance.stub(:upload_server_certificate).and_raise(new_error) 
    end 
end 

該規範:

it "should not upload a server certificate" do 
    provider.break_server_certificates!     # provider is defined and is an instance of the Provider AR model 
    client.post provider_server_certificates_path, params #client is a rack client that we use to test api interactions 
end 
現在210

,問題是任何時候我改變any_instance.stub在模擬中使用雙,格外一個partial double,這是最接近我已經能夠得到,像這樣的東西:

def break_server_certificates! 
    expect(self.iam).to receive(:upload_server_certificates).and_raise(new_error) 
end 

的方法支持,但由於我的測試做了一個真正的API交互,它再次在控制器中找到提供者,它不是Provider的同一個實例,所以當然方法已恢復爲默認值。

回答

0

存根在RSpec的3個測試雙打與allow製成:

foo = double("foo") 
allow(foo).to receive(:baz) { "baz" } 

但是你也可以通過suppling創建測試雙時哈希定義允許的方法:

foo = double("foo", baz: "baz") 
+0

我已經一直在允許,這可能是提供了我試圖存根的方法,這正在搞亂我。每當我做這樣的事情時,我最終會得到一個'Class does not implement:method''錯誤,即使我知道它的確如此。 – Eugene 2014-09-22 19:49:36

+0

也許如果你分享了更多的代碼,我們可以看到發生了什麼?有一件事要注意正確的對象被扼殺。 'any_instance'很方便,因爲它會影響通過模型上的'find'返回的任何內容 - 如果你想替換'any_instance',你需要另一種方法來附加存根。 – zetetic 2014-09-22 20:05:15

+0

謝謝,抱歉花了我很長時間纔回到你身邊。我編輯了我原來的問題,看到下面的所有內容編輯2.任何建議,你可以給我將不勝感激。 – Eugene 2014-09-24 12:43:01