2010-11-23 32 views
13

我想測試一個方法調用鏈中的某個方法是否獲取特定參數。例如,在下面的代碼中,MyModel必須接收方法offset的參數0。不幸的是下面的代碼不起作用。看起來不可能混用should_receive和stub_chain。我怎麼能解決這個問題?我使用的RSpec 2.stub_chain連同should_receive

MyModel.should_receive(:offset).with(0).stub_chain(:tag_counts, :offset, :limit, :order).and_return([]) # does not work! 

的代碼我試圖測試:

tags = taggable.tag_counts.offset(page-1).limit(per_page).where(*where_clause).order("count DESC") 

更新

我也貼在RSpec的谷歌集團的問題是大衛(RSpec的創造者)回答了它(感謝大衛):http://groups.google.com/group/rspec/browse_thread/thread/6b8394836d2390b0?hl=en

回答

8

這是我現在在我的規格中做的一個例子。這是一個有點不方便(許多行的原因),但它的工作原理:

SearchPaginationModel.stub(:tag_counts) { SearchPaginationModel } 
SearchPaginationModel.should_receive(:offset).with(0) { SearchPaginationModel } 
SearchPaginationModel.stub_chain(:limit, :where, :order) { [] } 
SearchPaginationModel.stub_chain(:tag_counts, :where, :count).and_return(1) 
SearchPaginationModel.search_tags(:page => "1") 

例如,這在測試該SearchPaginationModel.tag_counts.offset(0).limit(X).where(X).order(X)真的offset設定爲0。