Question

So I'm going through the CodeSchool Rspec track (I'm on level 4) and I like to rewrite the examples to reinforce what I'm learning. I set up a Dog class that mimics the Zombie class, and ran tests that are identical, but for some reason I'm getting the error:

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)>'

I don't understand why, here is the code:

CodeSchool Model:

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

My Model

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

Note: I don't use attr_accessible because I'm using Rails4.

The CodeSchool Specs

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

My Specs

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

Can anyone explain why I'm getting the NoMethodError? Also, I know the questions on this site usually learn towards the practical but hopefully understanding why I'm getting this error will help me write more practical tests later. Thanks.

Was it helpful?

Solution

iq must have a value before you can increment that. So you need to do is <% iq = 0 %> before self.iq += 3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top