Factory Girl with has many relationship (and a protected attribute)

我的梦境 提交于 2020-01-04 04:02:44

问题


I have this kind of relation:

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
  attr_protected :article_id
end

The default scenario inside controllers looks like:

@article = Article.create(:title => "foobar")
@comment = @article.comments.create(:content => "w00t")

I had tried to write those factories:

Factory.define :article do |f|
  f.title "Hello, world"
end

Factory.define :comment do |f|
  f.content "Awesome!"
  f.association :article
end

But my syntax is not correct about the association. It's a little bit tricky because of the comment's article_id protected attribute. So I think this should be better if I declare the association inside the article factory, but I don't see how to process.

Thanks for any help.


回答1:


You should do

Factory.define :comment do |f|
  f.content "Awesome!"
  f.article { |a| a.association(:article) }
end


来源:https://stackoverflow.com/questions/3634533/factory-girl-with-has-many-relationship-and-a-protected-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!