testing

Auto-Test Mundaine Validations

When you’re writing your spec files in RSpec, it is my belief that you should spec out even the validations that you add (validates_presence_of, validates_uniqueness_of, etc..). Even though these are core parts of Rails, your spec file should be able to be read by someone with little background in development and still get what is required of your application. Validating that a field is present and required is part of these specifications, so they should be there. However, testing to make sure something is always present isn’t necessarily exciting, and you’re basically doing the same thing over and over. Making sure that if a field is nil, it’s not saved to the database, and it give back an error. So I wrote something that will test to make sure that these fields are always valid. If this is already in RSpec, or something similar; or if you know a better way to do this, please let me know.

def validate_presence_of(klass, fields)
  fields.each do |field|
    it "should include #{field}" do
      lambda do
        instance = klass.create(field.to_sym => nil)
        instance.errors.on(field.to_sym).should_not be_nil
      end.should_not change(klass, :count)
    end
  end
end

Stick that in your spec helper file, and now you can just add

validate_presence_of(SomeClass, %w(afield another_field field3 ))

to your model specs, and you’ve just saved yourself alot of typing, and it’s still pretty clear what you’re trying to test.

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*Required Fields