首页 > 解决方案 > 如果方法被发送到不是模拟的对象,如何在 MiniTest 中断言?

问题描述

我知道我们可以使用 来检查方法是否发送到 Mock 对象expect,但是如何检查方法是否发送到不是 Mocks 的对象,而是应用程序中的实际对象?

动机:Sandi Metz 的演讲 'Magic Tricks of Testing' https://www.youtube.com/watch?v=URSWYvyc42M说对于单元测试传出命令方法调用(在她的演讲中解释),我们应该验证消息是发送。我正在尝试这样做,但我在 MiniTest 中发现的唯一东西是assert_send,它有一些问题:

  1. 它已被弃用。
  2. 它不考虑发送给接收对象的参数值。如果我运行assert_send([object, :method_called, 'argument 1', 'argument 2']),则断言将返回 true,即使object期望与 and 不同的字符串'argument 1'也是如此'argument 2'

我已经在网上搜索了 2 天的大部分时间。有人有想法么?

标签: ruby-on-railsrubyunit-testingmockingminitest

解决方案


想出了我自己问题的答案:)

发布这个以防其他人像我一样遇到麻烦。

使用Spy gem,您可以断言方法已被调用。

来自 Ilija Eftimov 的这篇文章 - https://ieftimov.com/test-doubles-theory-minitest-rspec

class BlogTest < Minitest::Test
  def test_notification_is_sent_when_publishing
    notification_service_spy = Spy.on(NotificationService, :notify_subscribers)
    post = Post.new
    user = User.new
    blog = Blog.new(user)

    blog.publish!(post)

    assert notificaion_service_spy.has_been_called?
  end
end

推荐阅读