是否应该做一些我不期望的事情?

hof*_*ffm 1 ruby testing rspec expectations stubbing

考虑以下两个琐碎的模型:

class Iq

  def score
    #Some Irrelevant Code
  end

end

class Person

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

end
Run Code Online (Sandbox Code Playgroud)

以下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
Run Code Online (Sandbox Code Playgroud)

当我运行此测试(或者更确切地说,类似的测试)时,看起来存根没有工作:

Failure/Error: person.iq_score
  NoMethodError:
    undefined method `iq_score' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

正如您可能猜到的那样,失败在上面标记为"错误"的行上.当该should_receive行被注释掉时,此错误消失.这是怎么回事?

Mer*_*ian 8

由于RSpec具有扩展的存根功能,现在以下方式是正确的:

Iq.should_receive(:new).with(person).and_call_original
Run Code Online (Sandbox Code Playgroud)

它将(1)检查期望(2)返回控制到原始函数,而不仅仅返回nil.