1

考虑以下两个简单模型:

class Iq

  def score
    #Some Irrelevant Code
  end

end

class Person

  def iq_score
    Iq.new(self).score   #error here
  end

end

以及以下 Rspec 测试:

describe "#iq_score" do

  let(:person) { Person.new }

  it "creates an instance of Iq with the person" do
    Iq.should_receive(:new).with(person)
    Iq.any_instance.stub(:score).and_return(100.0)
    person.iq_score
  end

end

当我运行这个测试(或者,更确切地说,一个类似的测试)时,存根似乎没有工作:

Failure/Error: person.iq_score
  NoMethodError:
    undefined method `iq_score' for nil:NilClass

正如您可能猜到的那样,失败出现在上面标有“此处错误”的行上。当该should_receive行被注释掉时,这个错误就消失了。这是怎么回事?

4

2 回答 2

8

由于 RSpec 扩展了 stubber 功能,现在以下方式是正确的:

Iq.should_receive(:new).with(person).and_call_original

它将 (1) 检查期望 (2) 将控制权返回给原始函数,而不仅仅是返回 nil。

于 2013-03-25T09:50:12.803 回答
4

您正在删除初始化程序:

Iq.should_receive(:new).with(person)

返回 nil,因此 Iq.new 为 nil。要修复,只需执行以下操作:

Iq.should_receive(:new).with(person).and_return(mock('iq', :iq_score => 34))
person.iq_score.should == 34 // assert it is really the mock you get
于 2012-07-04T08:00:11.307 回答