摩卡和嵌套对象

发布于 2024-08-23 23:47:57 字数 284 浏览 4 评论 0原文

如果这是一个愚蠢的问题,请原谅,我是嘲笑新手。

我可以使用 mocha 执行以下操作:

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

如何模拟嵌套对象?

假设我有一个属于某个人的产品,并且我想获取该人的名字。

在我的应用程序中,我可能会这样做:

product.person.first_name

如何使用模拟获得相同的结果?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画骨成沙 2024-08-30 23:47:57

作为 shingara 答案的替代方案,您可以使用 mocha 的 any_instance 方法“它将检测对类的任何实例的调用”。

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

它记录在:
http://mocha.rubyforge.org/classes/Mocha/ClassMethods.html# M000001

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

回心转意 2024-08-30 23:47:57

你需要先定义一个mock(),然后在产品上调用person时返回它


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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文