工厂女孩:验证关联的线索到未定义的方法是否有效? nil:Nilclass

Factory girl : validates associated leads to undefined method valid? for nil:Nilclass

我有模型 Studenthas_one :account

所有与输入相关的数据都存储在帐户内。学生模型只是在涉及到关系时发挥作用(其他一些模型属于学生)。

问题:我没法用厂妹测试。

 factory :student do
   end

因为我无法定义除此之外的任何内容。

我每次尝试 @student = FactoryGirl.create(:student) 得到的结果:

undefined method `valid?' for nil:NilClass

有任何修复吗?

附加代码

class Account < ActiveRecord::Base
belongs_to :account_holder, :polymorphic => true
...
end

factory :account do
sequence :name do |n|
  "Name#{n}"
end
  sequence :surname do |n|
    "Surname#{n}"
  end
  sequence :phone do |n|
    "8911222332#{n}"
  end
  sequence :email do |n|
    "somemail#{n}@mail.ru"
  end
  student
end

问题来源

学生有:

validates_associated_extended :account

这基本上是通常的 validate 但父模型提取错误。

因此,当 FactoryGirl 尝试创建学生时,它会验证帐户,即 nil

我试过这个:

before(:create) {|student| build(:account, :account_holder =>student )}

student factory 中,而在 account factory 中:

association :account_holder, :factory=>:student

但是还是不行。

factory :student do
  after :build do |student|
     student.account << create(:account, :account_holder => student) if student.account_holder.nil?
  end
end

这使您既可以拥有一个有效的学生,也可以指定一个帐户(如果您想强制一个)。 我认为 FactoryGirl 的最新版本甚至允许将其编写为惰性属性语法:

factory :student do
  account { create(:account) }
end