我正在尝试使用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
这是我的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
似乎这个测试应该通过,因为工厂是用客户端构建的。但我不确定为什么验证会导致错误。
答案 0 :(得分:0)
错误消息显示为expected ..... to be valid, but got errors: Client can't be blank
work = FactoryGirl.build(:work) # this returns an unsaved object
使用build
您尚未保存对象。对象是nil
。如果对象是nil
it is blank
您想要像这样
将对象保存在创建中work = FactoryGirl.create(:work) # this returns a saved object
现在
work.should be_valid
应该通过
更新:
我对你的`factories.rb'
的看法不够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
client
工厂中的work
属性字面上是空白的。这不会通过验证,也不会保存对象。在工厂中填写client
或在这样的创作中传递一些东西
work = FactoryGirl.create(:work, client: "fill in with client")