Bryce
Bryce

Reputation: 2872

Rails "update_attributes" skipping validation?

I have the following simplified model:

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

That's pretty straight forward. I'm testing it with RSpec/FactoryGirl, and have the following tests:

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

However, the second test fails. For some reason, "12" seems to be able to be saved into the database as a valid password. Why? The API states that update_attributes should not bypass any of the validations!

Upvotes: 1

Views: 2298

Answers (1)

John Naegle
John Naegle

Reputation: 8247

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

Upvotes: 3

Related Questions