2011-06-05 57 views
0

我想測試的方法是:幫助存根和模擬測試,如何使用一個模擬,也必須返回一個值?

def self.load_file(file) 
    lookup = '' 

    if file.extension.include? "abc" 
    lookup = file.extension 
    else 
    lookup = file.last_updated 
    end 

    @location = Location.find_by_lookup(lookup) 

    @location 
end 

所以我需要存根文件,以便它響應延伸和LAST_UPDATED電話。 我還需要模擬對file.last_updated的調用,因爲我想確保如果文件擴展名具有'abc',它不會通過擴展名查找,而是通過'last_updated'查找。

我該如何測試?

+0

你說要通過與擴展LAST_UPDATED查找名爲「abc」,但你代碼是相反的... – 2011-06-05 21:12:29

回答

1

你的流量會是這個樣子(替代「myclass」的類的實際名稱):

it "should lookup by last_updated for abc files" do 
    update_time = Time.now 
    # create a location to match this update_time here 
    file = double("file") 
    file.should_receive(:extension).and_return("abc") 
    file.should_receive(:last_update).and_return(update_time) 
    MyClass.load_file(file).should == Location.find_by_lookup(update_time) 
end 

it "should lookup by extension for all other files" do 
    # create a location to match the "def" extension here 
    file = double("file") 
    file.should_receive(:extension).twice.and_return("def") 
    file.should_not_receive(:last_update) 
    MyClass.load_file(file).should == Location.find_by_lookup("def") 
end 
相關問題