I have a many-to-many association between a Post and a Category model:
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
This works:
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) }
My problem it’s here:
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") }
When I run the test for reply_spec.rb I get this error:
> undefined method `category=' for #<Post:0x9e07564>
This is part that that is not working I think:
factories.rb:
category_ids category
Am I defining the nested attribute in a wrong way? What’s the proper one?
this post uses after_build hooks to create associations: Populating an association with children in factory_girl
Personally I like not having factories too complicated (makes them too specific imo), and instead instantiate any neccessary associations in the tests as needed.
factories.rb:
post_spec.rb:
(edit — since post object has associations to categorizations and not to categories directly)