RoR: Chained Stub using Mocha
Is it possible to stub an entire chain using Mocha? For example, I want to stub:
User.first.posts.find(params[:id])
such that it returns a predefin开发者_开发知识库ed 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)
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.
EDIT: 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
With this, you can call User.any_instance.stub_path('posts.find').returns(@post)
Based on http://viget.com/extend/stubbing-method-chains-with-mocha you can try:
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)
精彩评论