0

我在 a和模型many-to-many之间有关联:PostCategory

分类.rb:

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

  belongs_to :post
  belongs_to :category
end

类别.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) }

我的问题在这里:

工厂.rb:

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

  factory :category do
    name "Lorem"
  end

回复规格.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>

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

工厂.rb:

  category_ids category

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

4

1 回答 1

1

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

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

工厂.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))}
于 2012-11-24T10:58:22.060 回答