[英]RSpec stubbing and checking arguments when an object's constructor instantiates another
鉴于下面的代码,我将如何在 RSpec 测试中验证 B 类的构造函数使用正确的参数调用 A 类的构造函数?
class A
def initialize(*args)
end
end
class B < A
def initialize
super(1)
end
end
只要我不检查参数(省略“.with”),我的测试就可以工作
describe B do
describe '#new' do
it {
allow(A).to receive(:new).with(any_args)
B.new
expect(A).to have_received(:new).with(1)
}
end
end
添加参数检查给我以下错误:
B
#new
should have received new(1) 1 time (FAILED - 1)
Failures:
1) B#new should have received new(1) 1 time
Failure/Error: expect(A).to have_received(:new).with(1)
#<A (class)> received :new with unexpected arguments
expected: (1)
got: (no args)
这似乎表明 A 类的构造函数在没有参数的情况下被调用?
当您在B
的initialize
方法中调用super
时,它会在A
调用initialize
,而不是new
。 您可以测试A
的实例是否使用一个参数initialize
:
expect_any_instance_of(A).to receive(:initialize).with(1)
B.new
但是 RSpec 会抱怨你存根initialize
。
您最好检查副作用(为什么要调用super
?)或验证是否调用了 super:
expect_any_instance_of(B).to have_received(:super).with(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.