ruby-on-rails – 在RSpec中stub_model和mock_model有什么区别?

在RSpec中stub_model和mock_model有什么区别?到目前为止,我知道存根被用来阻止真正的方法被调用并返回一个预定义的值,而mock实际上是预期的,并且要求在接收器上调用该方法.

我也知道这些存根/模拟被用于允许孤立的测试,如控制器中没有触摸模型.但是,我仍然对这两种方法感到困惑,当时每个方法都被使用?细节和例子将非常感谢.非常感谢!

解决方法

stub_model

The stub_model method generates an instance of a Active Model model.

While you can use stub_model in any example (model,view,controller,helper),it is especially useful in view examples,which are inherently more state-based than interaction-based.

mock_model

The mock_model method generates a test double that acts like an Active Model
model. This is different from the stub_model method which generates an instance of a real ActiveModel class.

The benefit of mock_model over stub_model is that its a true double,so the examples are not dependent on the behaviour (or mis-behaviour),or even the existence of any other code.
If you’re working on a controller spec and you need a model that doesn’t exist,you can pass mock_model a string and the generated object will act as though its an instance of the class named by that string.

rspec docs:stub_modelmock_model

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...