RoR:使用 Mocha 的链式存根 [英] RoR: Chained Stub using Mocha
问题描述
是否可以使用 Mocha 存根整个链?例如,我想存根:
Is it possible to stub an entire chain using Mocha? For example, I want to stub:
User.first.posts.find(params[:id])
这样它就返回一个预定义的 post 实例而不是访问数据库.理想情况下,我想做类似的事情:
such that it returns a predefined post instance instead of accessing the database. Ideally, I'd want to do something like:
@post = Post.new
User.any_instance.stubs(:posts,:find).returns(@post)
如您所见,我将 'posts' 和 'find' 方法放在一起.显然这现在不起作用,但是有没有办法实现这种效果?谢谢.
As you can see, I'm stubbing out both the 'posts' and 'find' methods together. Obviously this isn't working right now, but is there a way I can achieve this effect? Thanks.
我在网上找到了以下方法,可以做到这一点:
I found the following online which hacks a way to do this:
module Mocha
module ObjectMethods
def stub_path(path)
path = path.split('.') if path.is_a? String
raise "Invalid Argument" if path.empty?
part = path.shift
mock = Mocha::Mockery.instance.named_mock(part)
exp = self.stubs(part)
if path.length > 0
exp.returns(mock)
return mock.stub_path(path)
else
return exp
end
end
end
end
有了这个,你可以调用 User.any_instance.stub_path('posts.find').returns(@post)
With this, you can call User.any_instance.stub_path('posts.find').returns(@post)
推荐答案
基于 http://viget.com/extend/stubbing-method-chains-with-mocha 你可以试试:
User.stubs(:first).returns(stub(:posts => stub(:find => @post)))
虽然我只能让这个表格起作用:
Although I could only get this form to work:
find = stub
find.stubs(:find).returns(@post)
posts = stub
posts.stubs(:find).returns(find)
User.stubs(:first).returns(posts)
这篇关于RoR:使用 Mocha 的链式存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!