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, "#{attribute_name} should be valid: #{test_object.[](attribute_name)}" 
      assert test_object.valid? 
      assert !test_object.errors.invalid?(attribute_name) 

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


And is used as easy as this:

def test_email_validation
    valid_emails = ['', '', '', '']
    invalid_emails = ['', '', 'matt@', 'matt.hall@com', '', '', '', '.@.']

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

Leave a Reply

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

You are commenting using your 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: