【问题标题】:Does should_receive do something I don't expect?should_receive 会做我没想到的事情吗?
【发布时间】:2012-07-04 08:13:04
【问题描述】:

考虑以下两个简单的模型:

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 行被注释掉时,这个错误就消失了。怎么回事?

【问题讨论】:

  • 您尝试删除with 方法还是添加and_return 方法?
  • 删除with 调用无效。鉴于尚未创建 Iq 实例,我将使用什么作为 and return 的参数?
  • mock_model(Iq).as_null_object
  • Iq.should_receive(:initialize).with(person) 呢?

标签: ruby testing rspec stubbing expectations


【解决方案1】:

您正在删除初始化程序:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 非常感谢!这对我帮助很大:)
    • 正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    相关资源
    最近更新 更多