Topic: Testing a Model with field not in database

1st post. smile

I've got a User model that uses the authorization method explained in Rails Recipes.  The database has a password_hash and password_salt field to hold the salt and hashed password.  When the user signs up I use a text_field named 'password' which is not in the database.

Here is the pertinent model information:

  validates_presence_of :password
  validates_confirmation_of :password
  validates_length_of :password, :within => 6..20

  def password=(pass)
    @password=pass
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt)
  end


I use the @password=pass in order to be able to validate the length, confirmation etc. of the password from the signup form.

How can I setup my fixtures and unit tests to test this user model while validating a "password" which is not in the database (a hashed password is kept, but not the password).

TIA

Last edited by clayton (2007-01-11 00:19:44)

Re: Testing a Model with field not in database

See this thread for some information on how to add validation to the password. I'm not sure if this is your problem, but good information to know anyway.

As for testing the password, fixtures can't help you here because you don't need to validate the password after it has been saved to the database, only when creating/updating the model while changing the password. So you can either create a new model in the test, or grab one from the database and change the password then test the validation.

def test_password_validation
  user = User.new(:password => 'foo')
  user.save
  assert_not_nil user.errors.on(:password)
end

Railscasts - Free Ruby on Rails Screencasts

Re: Testing a Model with field not in database

Ah...

I was expecting to be able to test my model validations using fixtures and testing, but I guess this is not the case.  Thanks for the example.

Re: Testing a Model with field not in database

I think that clayton was trying to set up a fixture where one or more fields included a calculated value. Here's how I set up a user model test fixture to handle a password and password salt value:

simple_user01:
  id: 1
  name: simple_user01
  salt: test_salt_value
  hashed_password: <%= UserTest.encrypted_password("passme", "test_salt_value") %>