Here’s a little snippet that I use to quickly form tests to ensure that my models validation is working correctly from within unit tests:

  # 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

Then, use it as follows in your unit tests:

  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

Can anyone suggest any improvements?


Creative Commons License


This work is licensed under a
Creative Commons Attribution 2.0 UK: England & Wales License.

6 Comments

  1. Fantastic, does the code have any license or can it be freely used?

  2. Updated to include a license now.

  3. Perfect. And congratulations for your blog, just discovered it but looks fantastic.

  4. I’m experiencing a strange problem while using the snippet.

    It seems to leave in the test db the last record of the valid values passed in the array, so the database is not totally cleaned after running the tests and therefore they are not repeatable.

  5. Yep. To me a similar thing occurred while testing.

    I tried a sequence of 4 validation tests in one test method. After the first run of ‘validation_tester’ the function leaves the object in an invalid state because the invalid tests are done _after_ the valid ones. Just switch the two blocks to leave the object in a valid state at the end.

    Solved the problem for me.

  6. Could we see your create_user method? Maybe your User model as well? I’ve been having a few issues, however I think it’s to do with custom validations module I use for certain validations that I use many times in my application.


Post a Comment

*
*