<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>adams.co.tt blog - tagged with activemodel</title>
  <id>http://adams.co.tt/</id>
  <updated>2012-04-12</updated>
  <author>
    <name></name>
  </author>
  <entry>
    <title>Duplicate Active Model validation errors</title>
    <link rel="alternate" href="http://adams.co.tt/blog/2012/04/12/duplicate-active-model-validation-errors/"/>
    <id>http://adams.co.tt/blog/2012/04/12/duplicate-active-model-validation-errors/</id>
    <published>2012-04-12</published>
    <updated>2012-04-12</updated>
    <author>
      <name></name>
    </author>
    <content type="html">&lt;p&gt;When attempting to test a model using Active Model validations, I came across a rather odd problem.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'active_model'

class Person
  include ActiveModel::Validations
  validates_length_of :name, :maximum =&amp;gt; 40, :message =&amp;gt; 'name too long'
  attr_reader :name
  def initialize(attrs)
    @name = attrs[:name]
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I was seeing duplicate &lt;code&gt;'name too long'&lt;/code&gt; error messages in the errors hash.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;describe Person do
  describe 'validation' do
    it 'should be invalid if name is too long' do
      person = Person.new(:name =&amp;gt; 'a' * 41)
      person.should_not be_valid
      person.errors[:name].should == ['name too long']
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above spec failed with the following message:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;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
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some further digging revealed that the &lt;code&gt;Person&lt;/code&gt; was being loaded twice by the &lt;code&gt;require&lt;/code&gt; method. &lt;code&gt;require&lt;/code&gt; was being called twice with two different paths, which both resolved to the file containing &lt;code&gt;Person&lt;/code&gt;. Removing the extra call to &lt;code&gt;require&lt;/code&gt; fixed the issue. This seems to be a problem particular to ruby 1.8.7.&lt;/p&gt;

&lt;p&gt;The runnable code examples reproducing this issue can be found &lt;a href="https://github.com/adscott/validations-spike"&gt;here&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
</feed>
