如何在MiniTest中存根? [英] How do I stub things in MiniTest?

查看:74
本文介绍了如何在MiniTest中存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试中,我想为类的任何实例添加罐头响应.

Within my test I want to stub a canned response for any instance of a class.

它看起来可能像这样:

Book.stubs(:title).any_instance().returns("War and Peace")

然后,每当我呼叫@book.title时,它都会返回战争与和平".

Then whenever I call @book.title it returns "War and Peace".

在MiniTest中有没有办法做到这一点? 如果是,您能给我一个示例代码片段吗?

Is there a way to do this within MiniTest? If yes, can you give me an example code snippet?

还是我需要摩卡咖啡?

MiniTest确实支持Mocks,但是Mocks对于我所需要的东西来说是过大的.

MiniTest does support Mocks but Mocks are overkill for what I need.

推荐答案

  # Create a mock object
  book = MiniTest::Mock.new
  # Set the mock to expect :title, return "War and Piece"
  # (note that unless we call book.verify, minitest will
  # not check that :title was called)
  book.expect :title, "War and Piece"

  # Stub Book.new to return the mock object
  # (only within the scope of the block)
  Book.stub :new, book do
    wp = Book.new # returns the mock object
    wp.title      # => "War and Piece"
  end

这篇关于如何在MiniTest中存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆