2017-03-05 79 views
0
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: "[email protected]", program_id: 1193, 287g: nil, active: true, call_office_id: 4 

在联系工厂创建的联系人记录中,program_id是1193,但程序表只有四个带有ID 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的现在抱怨说,“程序不能为空”。问题:如何创建联系工厂以满足验证?为什么社团如此艰难,比在ROR中创建社团更困难。谢谢阅读。

回答

0

此:

FactoryGirl.define do 
    program  #association 

创造了新的计划记录,这是作为关联附加(与其他一些ID,也可以是1193或任何其他ID)。

如果您不想创建任何新的程序记录,只需在工厂类中保留program_id 1即可。另外,请记住,您在空数据库中运行测试。 如果您在测试套件之前创建程序记录,并且明确指定其ID为1,则此工厂类定义将起作用。