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 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)
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)