mocha and nested objects

谁说胖子不能爱 提交于 2019-12-24 12:50:39

问题


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?


回答1:


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




回答2:


you need define a mock() before and return it when you call person on product


person = mock(:first_name => 'david')
product.expects(:person).return(person)

product.person #=> mockObject
product.person.first_name #=> david


来源:https://stackoverflow.com/questions/2378808/mocha-and-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!