rubytestingmockingstubbingruby-mocha

mocha and nested objects


Excuse if this is a silly question, I am new to mocking.

I am able to use mocha to do things like:

person.expects(:first_name).returns('David')

How can I mock a nested object?

Say I have a Product that belongs to a Person and I want to get the first name of that person.

In my app I might do it like this:

product.person.first_name

How would I get the same result using a mock?


Solution

  • as an alternative to shingara's answer, you could use mocha's any_instance method "which will detect calls to any instance of a class".

    Person.any_instance.expects(:first_name).returns('david')
    

    it's documented at:
    http://mocha.rubyforge.org/classes/Mocha/ClassMethods.html#M000001