Duplicate Active Model validation errors12th April 2012
When attempting to test a model using Active Model validations, I came across a rather odd problem.
require 'active_model' class Person include ActiveModel::Validations validates_length_of :name, :maximum => 40, :message => 'name too long' attr_reader :name def initialize(attrs) @name = attrs[:name] end end
I was seeing duplicate
'name too long' error messages in the errors hash.
describe Person do describe 'validation' do it 'should be invalid if name is too long' do person = Person.new(:name => 'a' * 41) person.should_not be_valid person.errors[:name].should == ['name too long'] end end end
The above spec failed with the following message:
Failures: 1) Person validation should be invalid if name is too long Failure/Error: person.errors[:name].should == ['name too long'] expected: ["name too long"] got: ["name too long", "name too long"] (using ==) # ./spec/person_spec.rb:17
Some further digging revealed that the
Person was being loaded twice by the
require was being called twice with two different paths, which both resolved to the file containing
Person. Removing the extra call to
require fixed the issue. This seems to be a problem particular to ruby 1.8.7.
The runnable code examples reproducing this issue can be found here.