Rspec:存根关系查找(链)

时间:2011-03-09 19:45:42

标签: ruby-on-rails rspec

控制器:

@organization.topics.find(params[:id])

如何使用Rspec在controller_spec中存根? (@organization正在我的规范助手中设置

我试过了:

controller.stub_chain(:topics, :find).with("37") { mock_topic }
Topic.stub(:find).with("37") { mock_topic }

以上两者似乎都不起作用。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

如果您有权访问@organization变量(表明您这样做),那么您应该能够:

@organization.stub_chain(:topics, :find).and_return(mock_topic)

我不相信(除非他们已将API更改为stub_chain,但我在文档中看不到任何此类性质)您可以在使用stub_chain时指定.with('37')。如果绝对有必要指定传递给find方法的变量(并且它很少),那么你将不得不走很长的路线:

# This line is attempting to fake-out the .topics association and
# just return a mock of *whatever*, since it's just an intermediary
# step to where we really want to get to.
topics = @organizations.stub!(:topics).and_return(mock_model(Topic))
topics.stub!(:find).with('37').and_return(mock_topic)

答案 1 :(得分:1)

不能只是:

@organizations.topics.stub!(:find).and_return(mock_whatever)