ruby-on-rails - 如果方法被发送到不是模拟的对象,如何在 MiniTest 中断言?
问题描述
我知道我们可以使用 来检查方法是否发送到 Mock 对象expect
,但是如何检查方法是否发送到不是 Mocks 的对象,而是应用程序中的实际对象?
动机:Sandi Metz 的演讲 'Magic Tricks of Testing' https://www.youtube.com/watch?v=URSWYvyc42M说对于单元测试传出命令方法调用(在她的演讲中解释),我们应该验证消息是发送。我正在尝试这样做,但我在 MiniTest 中发现的唯一东西是assert_send
,它有一些问题:
- 它已被弃用。
- 它不考虑发送给接收对象的参数值。如果我运行
assert_send([object, :method_called, 'argument 1', 'argument 2'])
,则断言将返回 true,即使object
期望与 and 不同的字符串'argument 1'
也是如此'argument 2'
。
我已经在网上搜索了 2 天的大部分时间。有人有想法么?
解决方案
想出了我自己问题的答案:)
发布这个以防其他人像我一样遇到麻烦。
使用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
推荐阅读
- javascript - 从 React 中的导入函数获取状态挂钩值
- swift - 我们可以以编程方式将 csv 文件存储在不同的 iCloud 帐户或苹果帐户中吗?
- python-3.x - Python 如何在 numpy 数组中找到与曲线路径相交的直线?
- windows - 如果将主机添加到 daemon.json,Windows Docker 守护程序会崩溃
- excel - 将 PDF 转换为 Word 并从第 2 页到最后一页
- python - 敌人射弹攻击快速问题的方法
- javascript - React useContext 在延迟后给出输出
- r - R:使用 Plotly() 的水平堆积条形图
- scala - 在模块上运行 SBT 命令
- ajax - 如何将 AJAX 错误直接发送到 ASP.NET Core MVC 中的开发人员异常页面?