当对象的构造函数实例化另一个时,RSpec存根和检查参数

时间:2016-03-30 13:43:40

标签: ruby rspec

鉴于下面的代码,我将如何在RSpec测试中进行验证 B类的构造函数调用类A的构造函数 正确的论点?

class A
  def initialize(*args)
  end  
end

class B < A
  def initialize
    super(1)
  end  
end

只要我不检查参数,我就可以进行测试(省略&#34; .with&#34;)

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类的构造函数被调用 参数

2 个答案:

答案 0 :(得分:1)

当您使用super initialize方法拨打B时,会在initialize中拨打A,而不是new。您可以使用一个参数测试A的实例是否接收initialize

expect_any_instance_of(A).to receive(:initialize).with(1)
B.new

但是RSpec会抱怨你initialize

答案 1 :(得分:0)

你可能最好检查一下副作用(你为什么要调用super?)或者验证是否调用了super:

  expect_any_instance_of(B).to have_received(:super).with(1)