factory_girl has_many:通过验证

时间:2010-09-24 06:53:30

标签: ruby-on-rails factory-bot

我有以下型号:

class Activity < ActiveRecord::Base
  has_many  :clientships, :dependent => :destroy
  has_many  :clients, :through => :clientships
end

class Clientship < ActiveRecord::Base
  belongs_to  :client
  belongs_to  :activity

  validates_presence_of :client_id
  validates_presence_of :activity_id, :unless => :new_record?
end

class Client < ActiveRecord::Base
  has_many  :clientships
  has_many  :activities, :through => :clientships
end

我无法创建:活动工厂,因为我收到验证错误“活动不能为空”。

我的工厂看起来像这样:

Factory.define :activity do |a|
  a.association :staff, :factory => :user
  a.clientships { |cs| [cs.association :clientship] }
end

Factory.define :clientship do |cs|
  cs.association(:client)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

我在规范中运行此工厂时遇到错误: @activity = Factory(:activity)

请帮助!

1 个答案:

答案 0 :(得分:3)

在这种情况下我总是这样做:

Factory.define :activity do |a|
  #whatever attributes
end

Factory.define :clientship do |cs|
  cs.association(:client)
  cs.association(:activity)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

所以在我的测试/规格中我使用

Factory :clientship

也许它不是那么干净,但对我来说更有意义......但是我不确定从联接表创建这样的关系是个好主意。

而且,总的来说,我首先要在belongs_to方面创建工厂中的关联,因为最终它对我来说不会产生问题。