使用Rspec存根链式方法 [英] Stubbing Chained Methods with Rspec

查看:83
本文介绍了使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆