gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:48:12 32 4
gpt4 key购买 nike

stub_model有什么区别和 mock_model在 RSpec 中?到目前为止,我知道 stub 只是用来防止调用真正的方法并返回预定义的值,而模拟实际上是期望并要求在接收器上调用该方法。

我也知道这些 stub /模拟用于允许隔离测试,例如在不接触模型的 Controller 中。但是我仍然对这两种方法感到困惑,究竟什么时候使用?详细信息和示例将不胜感激。非常感谢!

最佳答案

stub 模型

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.



模拟模型

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 文档: stub_modelmock_model

关于ruby-on-rails - RSpec 中的 stub_model 和 mock_model 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386375/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com