Why does RSpec fail on that validation?
I have these validations :
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
Then, i also have in my migration :
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
When i run rspec i get :
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
Why does it present these errors on level, sapphires, but it works ok for adventure_points ? Moreover, if i open a console and do User.new, i get the default values as expected. What is hapening here ?
The database defaults are not set until the model is saved. Try:
it "should have 100 adventure points" do user = User.create user.adventure_points.should == 100 end
Found the solution myself, pretty sneaky one. I had to run rake:test:prepare because the test database did not have fixtures data and was not prepared :P
精彩评论