Nice helper for testing model validation

December 3, 2007

I found this this morning in Mr. Matt’s blog. Is a fantastic helper method to save us work testing our ActiveRecord models validation, available under the Creative Commons Attribution 2.0 UK: England & Wales License.


# In test_helper.rb 
  # Give this function an array of invalid values, an array of valid values, the object and 
  # attribute name to test, and it will ensure that only valid values are allowed 
  def validation_tester ( valid_values, invalid_values, attribute_name, test_object ) 
    valid_values.each do |val| 
      test_object.[]=(attribute_name, val) 
      assert test_object.save, "#{attribute_name} should be valid: #{test_object.[](attribute_name)}" 
      assert test_object.valid? 
      assert !test_object.errors.invalid?(attribute_name) 
    end  

    invalid_values.each do |val| 
      test_object.[]=(attribute_name, val) 
      assert !test_object.save, "#{attribute_name} should NOT be valid: #{val}" 
      assert !test_object.valid? 
      assert test_object.errors.invalid?(attribute_name) 
    end

end

And is used as easy as this:


def test_email_validation
    valid_emails = ['matt@test.com', 'matt.hall@test.com', 'matt@test.ing.com', 'matt.hall@test.ing.com']
    invalid_emails = ['@test.com', 'test.com', 'matt@', 'matt.hall@com', '.matt@test.ing.co.uk', 'matt@@test.com', '', '.@.']

    u = create_user
    validation_tester( valid_emails, invalid_emails, 'email', u)
  end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: