【问题标题】:CodeSchool Rspec Example gives me NoMethodError: 'undefined method '+' for nil:NilClass'CodeSchool Rspec 示例给了我 NoMethodError: 'undefined method '+' for nil:NilClass'
【发布时间】:2014-02-18 17:03:27
【问题描述】:

所以我正在学习 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? 另外,我知道这个网站上的问题通常会学习实用,但希望理解我为什么会收到这个错误将帮助我以后编写更多实用的测试。 谢谢。

【问题讨论】:

  • 您还没有在新记录中初始化iq,所以它的值是nil,而您尝试增加它的尝试以这种方式失败。

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


【解决方案1】:

iq 必须有一个值才能增加它。所以你需要做的是&lt;% iq = 0 %&gt;之前self.iq += 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2012-08-08
    • 2014-09-05
    相关资源
    最近更新 更多