使用 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屋!