我需要一个至少包含两个条目的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
答案 0 :(得分: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
答案 1 :(得分: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