使用Rspec存根链式方法 [英] Stubbing Chained Methods with Rspec
问题描述
我想调用一个只会返回一条记录的named_scope,但是named_scope返回一个数组,这没什么大不了的,因为我可以将其与.first链接起来:
I want to call a named_scope that will only return one record, but the named_scope returns an array, that's not a big deal as I can just chain it with .first:
Model.named_scope(param).first
这有效,我苦苦挣扎的是如何对链接的电话进行存根处理.有人对我如何使用Rspec模拟实现这一目标有参考或答案吗?
and this works, what I am struggling with is how to stub the chained call. Does anyone have a reference or an answer on how I would go about achieving this with Rspec mocking?
推荐答案
我发现了一些问题.
Client.stub!(:named_scope).and_return(@clients = mock([Client]))
@clients.stub!(:first).and_return(@client = mock(Client))
这允许我给控制器打电话:
which allows me to call my controller:
@client = Client.named_scope(param).first
它可以工作,但是有更好的解决方案吗?
It works, but is there a better solution?
rspec 1.2.6的发布使我们可以使用stub_chain,这意味着它现在可以是:
The release of rspec 1.2.6 allows us to use stub_chain meaning it can now be:
Client.stub_chain(:named_scope, :chained_call).and_return(@clients = [mock(Client)])
这是我的头等大事,一如既往地检查api的细节:)
This was top of my head, as always check the api for specifics :)
这篇关于使用Rspec存根链式方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!