我想通過與has_many關聯的has_many來驗證具有validates_presence_of的Factory Girl的模型。儘管表單工作正常,而且我可以編寫一個手動填寫表單的測試,但我無法獲得有效的工廠。這個測試持續失敗:我如何測試has_many:通過關聯,還有一個validates_presence_of驗證與Rails中Factory Girl的關聯?
it "has a valid work factory" do
work = FactoryGirl.build(:work)
work.should be_valid
end
這裏的錯誤消息:
Work has a valid work factory
Failure/Error: work.should be_valid
expected #<Work id: nil, name: "Client Website", date: "2013-06-03 16:13:08", client: #<Client id: 1, name: "Client Number 4", client_code: "CN4", created_at: "2013-06-04 16:13:12", updated_at: "2013-06-04 16:13:12">, description: "A great new website for the client.", image: "/image.jpg", service: "Web", featured: true, created_at: nil, updated_at: nil> to be valid, but got errors: Client can't be blank
這是我的factories.rb文件:
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "person_#{n}@example.com"}
password "secret"
password_confirmation "secret"
factory :admin do
after(:create) {|user| user.add_role(:admin)}
end
end
factory :client do
sequence(:name) { |n| "Client Number #{n}"}
sequence(:client_code) { |n| "CN#{n}"}
end
factory :work do
name "Client Website"
client
date 1.day.ago
description "A great new website for the client."
image "/image.jpg"
service "Web"
featured true
end
end
我的工作模式:
class Work < ActiveRecord::Base
attr_accessible :client, :client_ids, :date, :description, :featured, :image, :name, :service
validates_presence_of :client_ids
validates_presence_of :date, :image, :name
validates_length_of :description, :in => 5..500, :allow_blank => true
validates_length_of :name, :in => 5..50
has_many :postings
has_many :clients, :through => :postings
end
我客戶端型號:
class Client < ActiveRecord::Base
attr_accessible :client_code, :name
validates_presence_of :client_code, :name
validates_uniqueness_of :name
validates_length_of :client_code, :is => 3
validates_length_of :name, :in => 5..50
has_many :postings
has_many :works, :through => :postings
end
看起來這個測試應該通過,因爲工廠正在建立一個客戶端。但我不確定爲什麼驗證會導致錯誤。
我應該提到,我得到了同樣的錯誤上創建3)'工作有一個有效的工作,工廠 故障/錯誤:工作= FactoryGirl.create(:work) ActiveRecord :: RecordInvalid: 驗證失敗:客戶端不能爲空 #./spec/integration/factories_spec.rb:81:in'' –
我可以通過瀏覽器創建一個新作品。 FactoryGirl.build(:work)還返回一個工作對象,其中包含由Factory Girl生成的關聯客戶端,並且該工作對象也可以正常工作。 –