1

我有以下简化模型:

class User
  attr_accessible :password
  validates :password, :presence => true
  validates_confirmation_of :password, :length => { :minimum => 4 }
end

这很简单。我正在使用 RSpec/FactoryGirl 对其进行测试,并进行了以下测试:

it "cannot create with password < 4 characters" do
  expect{ model = FactoryGirl.create(:user, :password => "12", :password_confirmation => "12") }.to raise_error
end

it "cannot update to password < 4 characters" do
  model = FactoryGirl.create(:user)
  model.should be_valid
  model.update_attributes({:password => "12", :password_confirmation => "12"})
  model.reload
  model.password.should_not eq("12")
end

但是,第二次测试失败。由于某种原因,“12”似乎可以作为有效密码保存到数据库中。为什么?API 声明update_attributes不应绕过任何验证!

4

1 回答 1

3

I don't think it is skipping validations.

I suspect this:

model.update_attributes({:password => "12", :password_confirmation => "12"})

is returning false. Password is probably not a column in your database, rather you probably have crypted_password and password_salt so reloading it does not read the password from the database (this would be bad)

Also, you probably want :

attr_accessible :password, :password_confirmation
于 2012-12-19T02:57:20.120 回答