【问题标题】:Factory Girl with has many relationship (and a protected attribute)工厂女孩有很多关系(和受保护的属性)
【发布时间】:2010-09-03 09:38:18
【问题描述】:

我有这种关系:

class Article < ActiveRecord::Base
  has_many :comments
end

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

控制器内部的默认场景如下所示:

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

我曾尝试编写那些工厂:

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

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

但是我对关联的语法不正确。由于评论的 article_id 受保护属性,这有点棘手。所以我觉得如果我在文章工厂里面声明关联应该会更好,但是我不知道怎么处理。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails testing ruby-on-rails-3 shoulda factory-bot


    【解决方案1】:

    你应该这样做

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

    【讨论】:

    • 非常感谢,mb14。快乐的 RoR3 发展! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多