问题描述
我正在尝试测试方法调用链中的方法之一是否获得特定参数.例如,在下面的代码中,MyModel 必须接收方法 offset
的参数 0.不幸的是,下面的代码不起作用.似乎不可能混合 should_receive 和 stub_chain.我怎么能解决这个问题?我正在使用 RSpec 2.
I am trying to test if in a method calling chain one of the methods get a specific parameter. In the below code for example MyModel must receive the parameter 0 for the method offset
. Unfortunately the code below does not work. It seems it is not possible to mix should_receive and stub_chain. How could I solve this? I am using RSpec 2.
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 Google Group 上发布了 David(RSpec 的创建者)回答的问题(感谢 David):http://groups.google.com/group/rspec/browse_thread/thread/6b8394836d2390b0?hl=en
推荐答案
这是我现在在我的规范中所做的一个例子.这有点不方便(因为有很多行),但它有效:
This is an example what I do in one of my specs now. It's a bit unhandy (cause of the many lines), but it works:
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 是设置.
This for example tests in SearchPaginationModel.tag_counts.offset(0).limit(X).where(X).order(X)
that really offset
0 is set.
这篇关于stub_chain 和 should_receive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!