2
votes

I need a has_many association that has at least two entries, how do I write the validation and how could this be tested using RSpec + factory-girl? This is what I got till now, but it fails with ActiveRecord::RecordInvalid: Validation failed: Bars can't be blank and I'm completely stuck on the RSpec test.

/example_app/app/models/foo.rb

class Foo < ActiveRecord::Base
  has_many :bars
  validates :bars, :presence => true, :length => { :minimum => 2}
end

/example_app/app/models/bar.rb

class Bar < ActiveRecord::Base
  belongs_to :foo
  validates :bar, :presence => true
end

/example-app/spec/factories/foo.rb

FactoryGirl.define do
  factory :foo do
     after(:create) do |foo|
       FactoryGirl.create_list(:bar, 2, foo: foo)
     end
  end
end

/example-app/spec/factories/bar.rb

FactoryGirl.define do
  factory :bar do
    foo
  end
end
2
:length is for strings, not relations. - benzado

2 Answers

4
votes
class Foo < ActiveRecord::Base
  validate :must_have_two_bars

  private
  def must_have_two_bars
    # if you allow bars to be destroyed through the association you may need to do extra validation here of the count
    errors.add(:bars, :too_short, :count => 2) if bars.size < 2
  end
end


it "should validate the presence of bars" do
  FactoryGirl.build(:foo, :bars => []).should have_at_least(1).error_on(:bars)
end

it "should validate that there are at least two bars" do
  foo = FactoryGirl.build(:foo)
  foo.bars.push FactoryGirl.build(:bar, :foo => nil)
  foo.should have_at_least(1).error_on(:bar)
end
2
votes

You want to use a custom validator

class Foo < ActiveRecord::Base
  has_many :bars
  validate :validates_number_of_bars

  private
  def validates_number_of_bars
    if bars.size < 2
      errors[:base] << "Need at least 2 bars"
    end
  end
end