ruby - Rails RSpec Test Does not Pass Correctly -
i'm writing model tests rspec cookbook
model. each user has_many
cookbooks, , each cookbook belongs_to
user. make sure cookbook
not created without user, wrote following test:
it "is invalid without user" expect(factorygirl.build(:cookbook, user: nil)).to be_invalid end
however, when running rspec
, following output:
1) cookbook invalid without user failure/error: expect(factorygirl.build(:cookbook, user: nil)).to be_invalid nomethoderror: undefined method `cookbooks' nil:nilclass
so, then, test error being raised, made test this:
it "is invalid without user" expect{factorygirl.build(:cookbook, user: nil)}.to raise_error(nomethoderror) end
however, test fails following output:
1) cookbook invalid without user failure/error: expect{factorygirl.build(:cookbook, user: nil)}.to raise_error(nomethoderror) expected nomethoderror nothing raised
if means anything, here factory cookbook:
require 'faker' factorygirl.define factory :cookbook |f| f.title "#{faker::name.first_name}'s recipes" f.description "#{faker::name.last_name}'s favorite recipes." f.user 1 end end
how should go writing model test makes sure user required when creating cookbook
?
within model may have validation or before callback calls bookshelves
on user model. when call be_invalid
on test, rspec calls valid?
on object built through factorygirl. object runs validations , error raised since tries call bookshelves
on nil
object (user).
when test error raising, doesn't happen because valid?
wasn't called on object. test raise error if way:
it "is invalid without user" expect{factorygirl.build(:cookbook, user: nil).valid?}.to raise_error(nomethoderror) end
however don't recommend make change on test make pass. should go model , check whether user present before calling bookshelves
on it. if don't so, app break whenever try create cookbook
without user.
Comments
Post a Comment