Class Abc
def initialize(target)
@target = target
end
def method_missing(name, *params, &block)
@target.send(name, *params, &block)
end
end
我有类似上面的代码,我想为上面的代码编写规范,这可能是测试此代码的最佳方法。
选项1. Abc
的测试实例对@target
的方法作出响应?
答案 0 :(得分:3)
您应该以测试行为而不是实现为目标,因此请不要存根并期望使用特定方法(除非字面上没有其他方法)。
也-您的示例不包含任何上下文。除非它为您的代码库增加了一些价值,否则拥有它几乎没有意义。
但作为一个高级答案:理想情况下,您将对每个可能的目标都有规格。您可能会考虑将这些提取为共享示例,并像这样
RSpec.describe Abc do
subject { described_class.new(target) }
context 'when the target is a string' do
let(:target) { String.new }
it_behaves_like 'a string'
end
context 'when the target is a CustomUser'
let(:target) { CustomUser.new }
it_behaves_like 'custom user behavior'
end
end
如您所见-这很无聊。但是我认为Abc
并不是现实生活中的示例,因此答案也有点抽象。
答案 1 :(得分:1)