具有关联的factory_girl工厂未正确分配ID

时间:2016-10-27 20:21:29

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

我有3个模仿这样的模型:

#user.rb
has_many :forums
has_many :posts

#forum.rb
belongs_to :user
has_many :posts

#post.rb
belongs_to :user
belongs_to :forum

我试图创建一组工厂,这些工厂共享所需的ID,这些工厂需要彼此关联。

#User factory
FactoryGirl.define do
  factory :user do
    sequence :email do |n|
      "testuser#{n}@postfactory.com"
    end

    password "password#1"
  end
end

#Forum factory
FactoryGirl.define do
  factory :forum do
    user
    name "Forum Name"
    description "Forum Description with a minimum character count of 20"
  end
end

#Post factory
FactoryGirl.define do
  factory :post do
    user
    forum
    title 'Post 1'
    description 'This is a test description for Post 1'
  end
end

当我使用以下命令运行我的规范测试时

user =      FactoryGirl.create(:user)
forum =     FactoryGirl.create(:forum)
post =      FactoryGirl.create(:post)

它在控制台中输出以下内容:

#<User id: 1, email: "testuser1@userfactory.com", created_at: "2016-10-27 20:10:36", updated_at: "2016-10-27 20:10:36">

#<Forum id: 1, name: "Forum Name", description: "Forum Description with a minimum character count o...", user_id: 2, created_at: "2016-10-27 20:10:36", updated_at: "2016-10-27 20:10:36">

#<Post id: 1, title: "Post 1", description: "This is a test description for Post 1", user_id: 3, forum_id: 2, created_at: "2016-10-27 20:10:36", updated_at: "2016-10-27 20:10:36">

如您所见,user_id增量,每个工厂都被创建,forum_id。我希望这些都具有1的ID而无需进行一些手工操作。我的设置错误做了什么

编辑:我有点看到我做错了什么。我只需要在我的规范测试中生成post,它将生成所需的工厂(论坛和用户)来创建post。但是,我注意到我生成了两个用户。

(byebug) User.count
2
(byebug) User.first
#<User id: 1, email: "testuser1@postfactory.com", created_at: "2016-10-27 20:30:33", updated_at: "2016-10-27 20:30:33">
(byebug) User.last
#<User id: 2, email: "testuser2@postfactory.com", created_at: "2016-10-27 20:30:33", updated_at: "2016-10-27 20:30:33">

知道为什么会这样吗?我尝试删除sequence :email部分并按标准执行。但是,我收到验证错误,表明已经收到电子邮件。出于某种原因,它试图运行user工厂两次,即使我在规范测试中只调用它一次。

1 个答案:

答案 0 :(得分:1)

每次调用FactoryGirl.create时,都会有一个新创建的用户,因此在运行此代码后:

user  = FactoryGirl.create(:user)
forum = FactoryGirl.create(:forum)
post  = FactoryGirl.create(:post)

实际上您创建了3个用户,因为您可以看到帖子有user_id: 3

如果您想创建论坛并与您创建的用户发帖,您可以将该用户分配到论坛并在创建时发布:

user  = FactoryGirl.create(:user)
forum = FactoryGirl.create(:forum, user: user)
post  = FactoryGirl.create(:post, user: user, forum: forum)

使用此代码,只有一个创建的用户。