I'm Rodrigo Vilina 👋!

A Software Gardener and Mentor, using Rust and Ruby to build high quality software.

A picture of myself

Preventing exceptions when validating ActiveRecord models

In some Rails applications, particularly legacy ones, we’ll find some Records that have validations that don’t handle errors properly.

En algunas aplicaciones Rails, usualmente las que crecen sin una buena planificación, se pueden encontrar registros (Records) con validaciones que no manejan los errores de manera adecuada.

Un primer paso para evaluar la existencia de este tipo de validaciones en una aplicación legacy puede ser un test que verifique que .new.save en los distintos records no levante excepciones; recordemos que la intención de las validaciones es agregar errores al modelo en cuestión.

We can use this short snippet for that:

RSpec.describe do
  ApplicationRecord.descendants.map do |klass|
    it "#{klass}.new.save should not raise an error" do
      expect { klass.new.save }.not_to raise_error
    end
  end
end

If we need to ensure this behavior in a case-by-case basis we can use RSpec shared_examples:

RSpec.shared_examples 'new record does not raise on save' do
  it 'does not raise an error when saving an empty record' do
    expect { described_class.new.save }.not_to raise_error
  end
end

I recommend using these techniques in legacy projects for identifying potentially uncared models and to correct any errors that may eventually exist in their validations.