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

时间:2012-07-03 20:26:23

标签: ruby testing rspec stubbing expectations

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

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行被注释掉时,此错误消失。发生了什么事?

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:4)

你正在删除初始化程序:

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

返回nil,所以Iq.new为零。要修复,只需这样做:

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
相关问题