繁体   English   中英

Rspec如何测试对单例类方法的类调用

[英]Rspec how to test class call to singleton class method

一个类User有一个调用has_one_time_password(encrypted: true)我想测试User类有该调用。

class User < ApplicationRecord
#...
has_one_time_password(encrypted: true)
#..
end

我努力了

expect(User).to receive(:has_one_time_password).with(encrypted: true)

但是我收到消息,该消息expected: 1, received: 0

我相信在运行您上面的Expect expect(User)... ,由于您的rails_helper.rb在其顶部有一行,因此class User < ApplicationRecord ... end已被加载到内存中:

require File.expand_path("../../config/environment", __FILE__)

因此,除非像下面这样手动加载它,否则将无法捕获它:

expect(User).to receive(:has_one_time_password).with(encrypted: true)
require 'user'

PS尚未对此进行测试。 此外,就个人而言,我宁愿测试“行为”而不是测试代码本身,因此也许我将对has_one_time_password实际执行的行为进行测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM