FactoryGirl字符串汇总has_many关系(即用户 - >博客 - >帖子)

时间:2012-10-11 21:56:05

标签: ruby-on-rails-3 factory-bot rspec-rails

假设我有三种模式:用户,博客和帖子。我的用户模型将包含:

User Model
  has_one :blog
  has_many :posts through: :blog


Blog Model
  belongs_to :user
  has_many :posts

Post 
  belongs_to :blog

当我做工厂时,我可以这样做:

FactoryGirl.define do
  factory :post do
    title "something"
    content "long text"
    blog 
  end
end

创建属于博客的帖子。我没看到的是我应该放入的内容:post以便FactoryGirl创建用户,然后创建属于该用户的博客,然后创建属于该博客/用户的帖子。我没有在FactoryGirl的文档中看到任何解决此问题的内容。

1 个答案:

答案 0 :(得分:1)

FactoryGirl.define do

  factory :post do
    title "something"
    content "long text"
    blog 
  end

  factory :blog do
    user
    # blog attributes
  end

  factory :user do
    # user attributes
  end
end

然后

@post = FactoryGirl.create(:post)
@blog = @post.blog
@user = @post.blog.user