无法在Factory Girl中创建嵌套属性?

时间:2012-11-24 04:04:25

标签: ruby-on-rails factory-bot

我在many-to-manyPost模型之间建立了Category关联:

categorization.rb:

class Categorization < ActiveRecord::Base
  attr_accessible :category_id, :post_id, :position

  belongs_to :post
  belongs_to :category
end

category.rb:

class Category < ActiveRecord::Base
  attr_accessible :name

  has_many :categorizations
  has_many :posts, :through => :categorizations  

  validates :name, presence: true, length: { maximum: 14 }
end

post.rb:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :category_ids

  has_many :categorizations
  has_many :categories, :through => :categorizations  

  accepts_nested_attributes_for :categorizations, allow_destroy: true

end

这有效:

post_spec.rb:

describe Post do

  let(:user) { FactoryGirl.create(:user) }
  let(:category) { FactoryGirl.create(:category) }
  before { @post = user.posts.build(title: "Lorem ipsum",
                                    content: "Lorem ipsum dolor sit amet",
                                    category_ids: category) }

我的问题在于:

factories.rb:

  factory :post do
    title "Lorem"
    content "Lorem ipsum"
    category_ids category
    user
  end

  factory :category do
    name "Lorem"
  end

reply_spec.rb:

describe Reply do

  let(:post) { FactoryGirl.create(:post) }
  let(:reply) { post.replies.build(content: "Lorem ipsum dolor sit amet") }

当我为reply_spec.rb运行测试时,我收到此错误:

> undefined method `category=' for #<Post:0x9e07564>

这是我认为不起作用的部分:

factories.rb:

  category_ids category

我是否以错误的方式定义嵌套属性?什么是合适的?

1 个答案:

答案 0 :(得分:1)

这篇文章使用after_build挂钩来创建关联:Populating an association with children in factory_girl

就个人而言,我不喜欢工厂太复杂(使它们太具体化),而是根据需要在测试中实例化任何必要的关联。

factories.rb:

factory :post do
  title "Lorem"
  content "Lorem ipsum"
  user
end

factory :category do
  name "Lorem"
end

post_spec.rb:

...
let(:post) {FactoryGirl.create(:post, :category => FactoryGirl.create(:category))}

(编辑 - 因为post对象与分类有关联,而不是直接与类别有关)

let(:post) {FactoryGirl.create(:post)}
let(:categorization) {FactoryGirl.create(:categorization, 
                                  :post=> post, 
                                  :category=> FactoryGirl.create(:category))}