我对rspec有一个问题,即在方法中创建一个外部对象,而不是使用该对象的模拟,创建实际对象。
Ruby代码:
module A
class B
def initialize
@my_variable = function_call
end
private
def function_call
external_object = ExternalObject.new(123)
{
key1: external_object.external_method.to_s,
key2: external_object.to_s
}
end
end
end
Rspec的:
describe A:B do
let(:mock_external_obj) { 'mock_ext_obj' }
let(:mock_external_obj_to_s) { 'mock_ext_obj_to_str' }
before do
allow(ExternalObject).to receive(:new).and_return(mock_external_obj)
allow(mock_external_obj).to receive(:to_string).and_return(mock_external_obj_to_s)
allow(mock_external_obj).to receive(:external_method).and_return(my_variable)
end
subject { described_class.new }
context 'does something' do
it 'does something else' do
expect(subject.my_variable).to eq({
key1: mock_external_obj_to_s,
key2: mock_external_obj_to_s
})
end
end
end
在上面的示例中,我希望ExternalObject.new(123)
返回mock_external_obj
。相反,它实际上是调用ExternalObject.new(123)
和external_object.external_method.to_s
来调用实际的外部对象的方法。