describeUserdodescribe"validations"dobeforedo@user=User.new:name=>"foo",:email=>"bar@foo.com"endit"should be valid"do@user.shouldbe_validendit"should not validate presence of :name"do@user.name=nil@user.should_notbe_validendit"should not validate length of :name"do@user.name="foo"*20@user.should_notbe_validendit"should not validate uniqueness of :email"do@user.saveUser.new(@user.attributes).should_notbe_validendendend
be_valid 可以讓 @user 先把 save 以前的 validation 都跑過, 並且預期 return true
當然若要直接 save 以預期結果的話, 可以改寫成
12
@user.save.should==true@user.save.should==false
或(可讀性較佳的寫法)
12
@user.save.shouldbe_true@user.save.shouldbe_false
謎之聲: 每個 validation 都要這樣寫好累 XD
當然上述的範例中除了麻煩之外, 當然 User 有追加了新的 validation 時, before 的 User.new 也要跟著對應, 倘若有很多需要 create user model 的 spec 時, 改起來就會很痛苦