class Program < ActiveRecord::Base
has_many :contacts
class Contact < ActiveRecord::Base
belongs_to :program
FactoryGirl.define do
factory :contact do
sequence(....
...
program_id 1 #foreign key
program #association
(byebug) contact
Contact id: 949, display_name: "Contact-3", business_phone: "1234567894", fax_number: "1234567894", created_at: "2017-03-05 00:43:24", updated_at: "2017-03-05 00:43:24", first_name: "First-4", last_name: "Last-4", middle_initial: "4", email: "Email4@Something.Com", program_id: 1193, 287g: nil, active: true, call_office_id: 4在使用contact factory创建的contact记录中,program_id为1193,但program表中只有4条记录,ids为1-4。不确定1193的来源。此时,rspec测试或多或少成功了。但是,一旦将下面的验证代码添加到联系人模型中,rspec测试就会失败。
为计划添加了关联验证的联系人模型
class ProgramValidator < ActiveModel::Validator
def validate(record)
if record.program.nil?
record.errors[:base] << "Program cannot be blank"
end
end
end
class Contact < ActiveRecord::Base
belongs_to :program
validates_with ProgramValidator现在运行rspec时,它会报告“程序不能为空”。问:如何创建contact工厂以满足验证要求?为什么关联如此困难,比在ROR中创建关联难得多。感谢您的阅读。
发布于 2017-03-05 20:07:16
根据Factory Girl的文档,试着这样做:
factory :contact do
# ...
association :program, factory: :program
end有关工厂女工协会的更多信息,请访问以下链接:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations
发布于 2017-03-05 20:18:56
这一点:
FactoryGirl.define do
program #association创建新的Program记录,该记录作为关联附加(具有某个其他id,也可以是1193或任何其他id)。
如果不想创建任何新的程序记录,只需在工厂类中保留program_id 1即可。另外,请记住您是在空数据库中运行测试的。如果您创建Program record,例如,在您的测试套件之前创建Program record,并显式地将其ID指定为1,则此工厂类定义将起作用。
https://stackoverflow.com/questions/42603206
复制相似问题