2

我需要一个至少有两个条目的 has_many 关联,我如何编写验证以及如何使用 RSpec + factory-girl 对其进行测试?这是我到目前为止所得到的,但它失败了ActiveRecord::RecordInvalid: Validation failed: Bars can't be blank,我完全陷入了 RSpec 测试。

/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
4

2 回答 2

4
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
于 2012-06-26T15:29:05.447 回答
2

您想使用自定义验证器

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
于 2012-06-26T15:25:05.777 回答