Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Duplicate validation error messages during testing

I'm getting some weird validation behavior: it's duplicating my validation error messages and I can't figure out what's causing it... it doesn't do this in the rails console.

Here is the validation from my Phone model:

# phone.rb
validates :number, :length => { :minimum => 3 }

My spec:

require 'spec_helper'

describe Phone do
  it "requires a number" do
    user = User.make!
    @p = Phone.new(number:nil,user_id:user.id,type:2)
    @p.valid?
    puts @p.errors.inspect 
    @p.should have(1).error_on(:number)
  end

My test results:

# rspec and machinist
#<ActiveModel::Errors:0x000000036f1258 @base=#<Phone id: nil, user_id: 614, kind: nil, number: nil, created_at: nil, updated_at: nil>, @messages={:number=>["is too short (minimum is 3 characters)", "is too short (minimum is 3 characters)"]}>
F

Failures:

  1) Phone requires a number
     Failure/Error: @p.should have(1).error_on(:number)
       expected 1 error on :number, got 2
     # ./spec/models/phone_spec.rb:11:in `block (2 levels) in <top (required)>'

Finished in 0.50988 seconds
1 example, 1 failure

As you can see, I'm getting "is too short (minimum is 3 characters)" twice... It's also /only/ happening during testing. Any ideas?

Thanks!

like image 673
wulftone Avatar asked Sep 23 '11 19:09

wulftone


1 Answers

The problem is in the line:

Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }

in the spec_helper.rb file, in the Spork.each_run block

If you change the method 'load' to 'require', it fixes the problem.

Or if you have a recent enough version of Spork, you can remove the line altogether. I am pretty sure the error is caused when someone is installing a newer version Spork(0.9.0+) with old instructions, because the line:

Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }

doesn't even has to be stated explicitly in the spec_helper.rb file anymore. If it is then when the load method is used in the spec_helper.rb file, it reloads the files specified , most likely the cause of the strange RSpec duplicate validations errors.

like image 191
Rebekah Waterbury Avatar answered Sep 27 '22 16:09

Rebekah Waterbury