简体   繁体   English

Rspec-在私有方法中模拟对象

[英]Rspec - Mocking an object in private method

In our application, we have written after_create/update/delete callbacks for some interested domain models. 在我们的应用程序中,我们为一些感兴趣的域模型编写了after_create / update / delete回调。 Inside of these models we create a new Audit model that xmlizes the necessary data of the changed model and store it in the Audit table. 在这些模型中,我们创建了一个新的Audit模型,该模型对更改后的模型的必要数据进行xml处理并将其存储在Audit表中。 As an example, the after_create callback of Consultant model looks as below: 例如,顾问模型的after_create回调如下所示:

def after_create
xml = #private xmlize() is called which returns the data of new Consultant object
audit = Audit.new :data=>xml.to_s
audit.save
end

Now, I would like to either mock the audit object to see if its save method is called using RSpec. 现在,我想模拟审计对象,以查看是否使用RSpec调用了其保存方法。 Or even better, if there is a way to regex the contents of the xml through RSpec, I would be glad to learn how to do it through Ruby in Rails environment. 甚至更好的是,如果可以通过RSpec对xml的内容进行正则表达式,我将很高兴学习如何通过Ruby in Rails环境来实现。

You can't naturally mock the Audit object because it's constructed within the method. 您自然不能嘲笑Audit对象,因为它是在方法中构造的。

What you might want to do is create and inject (somwhere ...) an AuditFactory, and use that to create the Audit object. 您可能想做的是创建并注入一个AuditFactory,然后使用它来创建Audit对象。

Then the factory and the audit can both be mocked, with an expectation that the mock factory creates the mock audit, and that the audit's save method is called. 然后可以模拟工厂和审计,并期望模拟工厂创建模拟审计,并调用审计的save方法。

The expectation on the factory could also be set to expect the correct xml. 也可以将对工厂的期望设置为期望正确的xml。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM