Coda Chang Coda Chang - 5 months ago 9
Ruby Question

Rails instance object valivate

I was trying to practice

Rspec
, but seems I was confused about some rails part.

Here is Zombie.rb

class Zombie < ActiveRecord::Base
validates :name, presence: true
has_many :tweets
def hungry?
true
end
end


It seems when I create a Zombie instance, it will check the
name
attribute.
So, I wrote these
Rspec
code.

it 'should not be hungry after eating' do
@zombie = Zombie.create
@zombie.should_not be_valid
@zombie.hungry?.should be_truthy
end


Why it will pass? If the
@zombie
is not valid, why
@zombie.hungry?
will still return
true

Answer

because your hungry? method always returns true

be_truthy # passes if obj is truthy (not nil or false) even if your object is nil it's returns true

be_truthy

z = Zombie.create - It will not be created because of validation

z.hungry? => true 

so your test passed