CodeSchool Rspec示例给出了NoMethodError:'undefined method'+'for nil:NilClass'

时间:2014-02-18 17:03:28

标签: testing rspec ruby-on-rails-4 rspec-rails nomethoderror

所以我正在通过CodeSchool Rspec轨道(我在4级),我喜欢重写这些例子来强化我正在学习的东西。我设置了一个模仿Zombie类的Dog类,并运行了相同的测试,但出于某种原因我收到了错误:

1) Dog is a genius dog
   Failure/Error: before { dog.learn_trick }
   NoMethodError:
     undefined method `+' for nil:NilClass
   # ./app/models/dog.rb:19:in `learn_trick'
   # ./spec/models/dog_spec.rb:23:in `block (2 levels) in <top (required)>'

2) Dog is not a dummy dog
   Failure/Error: before { dog.learn_trick }
   NoMethodError:
     undefined method `+' for nil:NilClass
   # ./app/models/dog.rb:19:in `learn_trick'
   # ./spec/models/dog_spec.rb:23:in `block (2 levels) in <top (required)>'

我不明白为什么,这是代码:

CodeSchool模型:

class Zombie < ActiveRecord::Base
  attr_accessible :name
  validates :name, presence: true

  def eat_brains
    self.iq += 3
  end

  def dummy?
    iq < 3
  end

  def genius?
    iq >= 3
  end
end

我的模特

class Dog < ActiveRecord::Base
  validates :name, presence: true

  def learn_trick
    self.iq += 3
  end

  def genius?
    iq >= 3
  end

  def dummy? 
    iq < 3
  end
end

注意:我不使用attr_accessible,因为我使用的是Rails4。

CodeSchool规范

describe Zombie do
  let(:zombie) { Zombie.new }
  subject { zombie }

  before { zombie.eat_brains }

  it 'is not a dummy zombie' do
    zombie.should_not be_dummy
  end

  it 'is a genius zombie' do
    zombie.should be_genius
  end
end

我的规格

describe Dog do
  let(:dog) { Dog.new }
  subject { dog }

  before { dog.learn_trick }

  it "is not a dummy dog" do
    dog.should_not be_dummy
  end 

  it "is a genius dog" do
    dog.should be_genius
  end 
end

任何人都能解释为什么我会收到NoMethodError吗? 另外,我知道这个网站上的问题通常会向实际学习,但希望了解为什么我收到此错误会帮助我稍后编写更多实际测试。 谢谢。

1 个答案:

答案 0 :(得分:0)

iq必须有一个值才能增加它。所以你需要在self.iq + = 3

之前做<% iq = 0 %>