Topic: Unit Testing

Hi,
   All i need a help for unit/testing, anyone give me the url of complete book of testing in ror.
  I got the code from google but i need code sample with explination.here my problem is that, i am trying to write the code for testing are below

def self.authenticate(username, password)

    contact = Contact.find(:first, :conditions => ['username = ?', username])

    if ( contact.blank? || contact == nil || (Digest::SHA256.hexdigest(password + contact.password_salt) != contact.password_hash) )
        raise "Username or password invalid in model"  # This will raise an exception if the above comparison condition fails
    else
      return contact
    end

can any one make me a reply for this,with explination if possible.
  thanks

Re: Unit Testing

I'm assuming this code is in your Contact model? In that case you would want to write a couple tests in the "contact_test.rb" file for this method. One will check that it returns the contact upon successfully logging in, another will check that it raises an error if it is unsuccessful.

The first thing you need to do is add fixtures to your "contacts.yml" file. This way you have some test data to play with. The hard part is setting the "password_hash" and "password_salt" columns. To do this, I would try creating a couple contacts in "script/console" and copying over their values for these columns. Make sure to remember what password you typed in for each.

Then it's just a matter of creating the two tests to check the behavior:

# in contact_test.rb
def test_valid_authentication
  assert_equal contacts(:foo), Contact.authenticate('foo', 'bar')
end

def test_invalid_authentication
  assert_raise RuntimeError do
    Contact.authenticate('foo', 'wrong_password')
  end
end


Replace "foo" and "bar" with whatever values you are using in the fixtures. Hope that helps.

Railscasts - Free Ruby on Rails Screencasts

Re: Unit Testing

hi, above code belongs to contact model,there is also code

has_many :relationships
  has_many :babies, :through => :relationships

  attr_accessor :password, :password_confirmation

I have to write the test code for above contact model code or not,

in that model the code for validation is

validates_uniqueness_of :username ,:if => Proc.new { |contact| contact.signup_step > 0 }
  validates_format_of :email, :if => Proc.new { |contact| contact.signup_step < 1 }, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

also a code for password is

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

  def password_confirmation=(confirm)
    @password_confirmation = confirm
  end
Make me reply if possible
Thanks

Last edited by kaushik (2007-04-25 02:46:18)