2011-05-09 39 views
18

雖然我的問題是非常簡單的,我沒能找到在這裏的答案參數:RSpec的成株:返回

我如何存根的方法和對確實陣列的方法返回參數本身(例如-operation)?

事情是這樣的:

interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>) 

回答

28

注:存根方法已被棄用。請參閱this answer爲現代的方式來做到這一點。


stub!可以接受塊。該塊接收參數;塊的返回值是存根的返回值:

class Interface 
end 

describe Interface do 
    it "should have a stub that returns its argument" do 
    interface = Interface.new 
    interface.stub!(:get_trace) do |arg| 
     arg 
    end 
    interface.get_trace(123).should eql 123 
    end 
end 
+0

謝謝,這正是我一直在尋找的! 我知道答案必須簡單:) – SirLenz0rlot 2011-05-09 15:55:03

+0

@SirLenzOrlot,不客氣!感謝您的選中標記和快樂的黑客行爲。 – 2011-05-09 16:15:39

+0

這可以結合序列發揮作用的情況(例如,第一次調用它返回參數,下次它返回「斷開」)? – SirLenz0rlot 2011-10-13 12:35:47

1

您可以使用allow(存根)代替expect(模擬):

allow(object).to receive(:my_method_name) { |param1, param2| param1 } 

使用命名參數:

allow(object).to receive(:my_method_name) { |params| params[:my_named_param] } 

這是一個活生生的例子:

我們假設我們有一個S3StorageService,使用upload_file方法將我們的文件上傳到S3。該方法將S3直接URL返回到我們上傳的文件。

def self.upload_file(file_type:, pathname:, metadata: {}) … 

我們要存根很多原因上傳(離線測試,性能改進...):

allow(S3StorageService).to receive(:upload_file) { |params| params[:pathname] } 

存根只返回文件路徑。