我正在尝试使用 Factory Girl 测试一个模型,该模型在 has_many 上具有 validates_presence_of :通过关联。尽管表单运行良好,并且我可以编写一个手动填写表单的测试,但我无法获得有效的工厂。此测试一直失败:
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
这是我的 factory.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
看起来这个测试应该通过,因为工厂是与客户一起建造的。但我不确定为什么该验证会导致错误。