我需要一個至少有兩個條目的has_many關聯,我如何編寫驗證以及如何使用RSpec + factory-girl測試它?這是我到現在爲止,但它與ActiveRecord::RecordInvalid: Validation failed: Bars can't be blank
失敗,我完全卡在RSpec測試。has_many至少有兩個條目
/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
/示例應用內/規格/工廠/ 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
':length'是字符串,而不是關係。 – benzado