2011-02-23 112 views
1

我有這些驗證:爲什麼RSpec在驗證失敗?

it "should have 100 adventure points" do 
    user = User.new 
    user.adventure_points.should == 100 
end 

it "should be level 1" do 
    user = User.new 
    user.level.should == 1 
end 

it "should have 10 sapphires" do 
    user = User.new 
    user.sapphires.should == 10 
end 

然後,我也有我的移民:

t.string :name,       :limit => 20 
    t.integer :strength_points,    :default => 0 
    t.integer :dexterity_points,    :default => 0 
    t.integer :magic_points,     :default => 0 
    t.integer :accuracy_points,    :default => 0 
    t.integer :health_points,    :default => 0 
    t.integer :level,      :default => 1 
    t.integer :adventure_points,    :default => 100 
    t.integer :sapphires,     :default => 10 
    t.integer :duel_wins,     :default => 0 
    t.integer :duel_losses,     :default => 0  
    t.string :image_url  
    t.integer :strength 

當我運行RSpec的我得到:

A new User 
    is not valid without a name 
    is not valid without a first class 
    is not valid without a password 
    should have 100 adventure points 
    should be level 1 (FAILED - 1) 
    should have 10 sapphires (FAILED - 2) 

Failures: 

    1) A new User should be level 1 
    Failure/Error: user.level.should == 1 
     expected: 1 
      got: nil (using ==) 
    # ./spec/models/user_spec.rb:28 

    2) A new User should have 10 sapphires 
    Failure/Error: user.sapphires.should == 10 
     expected: 10 
      got: nil (using ==) 
    # ./spec/models/user_spec.rb:33 

爲什麼會出現這些錯誤在水平上,藍寶石,但它適合adventure_points?此外,如果我打開一個控制檯並執行User.new,我會得到預期的默認值。這裏開什麼東西?

回答

1

自己找到了解決方案,很狡猾的一個。我不得不跑耙:測試:準備,因爲測試數據庫沒有燈具數據,並沒有準備:P

1

數據庫默認值在保存模型之前未設置。試試:

 
it "should have 100 adventure points" do 
    user = User.create 
    user.adventure_points.should == 100 
end 
+0

我想到了這一點,但它不起作用。儘管它使用User.new設置,但您可以看到adventure_points運行良好 – Spyros 2011-02-23 02:23:31