0

とモデルmany-to-manyの間に関連付けがPostあります: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) }

私の問題はここにあります:

factorys.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>

これは私が思うにそれが機能していない部分です:

factorys.rb:

  category_ids category

ネストされた属性を間違った方法で定義していますか?適切なものは何ですか?

4

1 に答える 1

1

この投稿では、after_buildフックを使用して関連付けを作成します。factory_girlの子との関連付けを設定します

個人的には、ファクトリが複雑になりすぎず(具体的なimoになりすぎる)、代わりに必要に応じてテストで必要な関連付けをインスタンス化するのが好きです。

factorys.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))}

(編集-投稿オブジェクトには、カテゴリに直接関連付けられているのではなく、カテゴリに関連付けられているため)

let(:post) {FactoryGirl.create(:post)}
let(:categorization) {FactoryGirl.create(:categorization, 
                                  :post=> post, 
                                  :category=> FactoryGirl.create(:category))}
于 2012-11-24T10:58:22.060 に答える