Duplicate Active Model validation errors

12th 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]

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 = => 'a' * 41)
      person.should_not be_valid
      person.errors[:name].should == ['name too long']

The above spec failed with the following message:


  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 method. 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.

blog comments powered by Disqus