1

我想尝试测试一个对象是否在特定情况下使用优化。所以我有这种代码

 class Bar
  attr_reader :n
  def initialize(n)
    @n=n
  end

  def a
    if @n <= 3
      b1
    else
      b2
    end
  end

  def b1
    @n+=1
  end

  def b2
    @n+=1 ##super fast addition
  end
end

我尝试编写这样的 rspec

bar=Bar.new(5)
allow(bar).to receive(:b2).and_call_original

bar.a
expect(bar).to receive(:b2).once
expect(bar.n).to eq 6

但它不起作用......你知道这可能吗?如果是的话怎么办?

4

1 回答 1

4

您应该在方法调用之前receive放置期望。你也可以合并成一行:allowexpect

bar = Bar.new(5)
expect(bar).to receive(:b2).once.and_call_original
bar.a
expect(bar.n).to eq 6
于 2014-09-01T14:26:25.507 回答