如何指定与factory_bot的关联?

时间:2018-04-27 11:11:57

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

例如,我有两个模型,一个用户和一个帖子。帖子属于用户,用户有很多帖子

#spec/factories/post.rb
FactoryBot.define do
  factory :post do
    user
    body Faker::Movie.quote
    posted_at "2018-04-03 13:33:05"
  end
end

#spec/factories/user.rb
FactoryBot.define do 
  factory :user do 
    first_name 'Jake'
  end
end

在测试中使用Rspec我想这样做:

user = create(:user, first_name: 'Barry') #id 1
post = create(:post, user: user)

我希望post的user_id为1但是它之前创建了另一个用户而user_id是2.

如何使用factory_bot / factory_girl创建对象时指定关联?

2 个答案:

答案 0 :(得分:12)

您应该使用explicit个关联,而不是implicit个关联:

#spec/factories/post.rb
FactoryBot.define do
  factory :post do
    association :user    # <<<--- here the change
    body Faker::Movie.quote
    posted_at "2018-04-03 13:33:05"
  end
end

#spec/factories/user.rb
FactoryBot.define do 
  factory :user do 
    first_name 'Jake'
  end
end

https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md

答案 1 :(得分:0)

另一个选择是在父级中使用#trait方法。

FactoryBot.define do
  factory :post do
    user nil
    body Faker::Movie.quote
    posted_at "2018-04-03 13:33:05"
  end
end

FactoryBot.define do 
  factory :user do 
    first_name 'Jake'
  end

  trait :with_post do
    after(:create) do |user|
      create(:post, user_id: user.id)
    end
  end
end

FactoryBot.create(:user, :with_post)