如何模拟 Rspec 中 class 之外的方法?
How to mock a method that is outside of a class in Rspec?
我必须模拟一个与任何 class 无关的方法。有人可以帮助我吗?
是这样的:
#device.rb
require_relative 'common'
class Device
def connect_target(target)
status = connect(target)
return status
end
end
#common.rb
def connect(target)
puts "connecting to target device"
end
我必须为设备 class 中的 "connect_target" 编写单元测试
通过模拟 common.rb
中的外部方法
I have to mock a method which is not associated with any class.
不存在不与任何模块关联的方法。 Ruby中只有一种方法:模块的实例方法(或类,它们是模块)。
connect
被定义为 Object
的 private
实例方法。
你会像这样嘲笑它:
allow(some_device).to receive(:connect)
请注意,无论如何定义方法都没有关系:这里没有提到 Device
或 Object
。
我必须模拟一个与任何 class 无关的方法。有人可以帮助我吗?
是这样的:
#device.rb
require_relative 'common'
class Device
def connect_target(target)
status = connect(target)
return status
end
end
#common.rb
def connect(target)
puts "connecting to target device"
end
我必须为设备 class 中的 "connect_target" 编写单元测试 通过模拟 common.rb
中的外部方法I have to mock a method which is not associated with any class.
不存在不与任何模块关联的方法。 Ruby中只有一种方法:模块的实例方法(或类,它们是模块)。
connect
被定义为 Object
的 private
实例方法。
你会像这样嘲笑它:
allow(some_device).to receive(:connect)
请注意,无论如何定义方法都没有关系:这里没有提到 Device
或 Object
。