views:

18

answers:

1

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)

A: 

I asked a similar question (and a way to solve this) here: http://stackoverflow.com/questions/4008681/how-to-mock-an-instance-method-of-an-already-mocked-object

As that question proves, not sure if it's the right way to go.

pjaspers
I found something on StackOverflow that sorta does what we want to do. Check the edit section of my question.
pushmatrix