FactoryBot creates records even when a record is provided

Viewed 783

I use factorybot to create records in development sometimes. However, it's creating a bunch of extra data that I wasn't expecting.

I have two factories:

FactoryBot.define do
  factory :user do
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { "#{first_name}.#{last_name}@example.com" }
  end

  factory :post do
    user { create(:user) }
    title { Faker::Lorem.sentence }
  end
end

If I run FactoryBot.create(:post) in the rails console, it will create a new post with a new user. What I didn't expect is that if I do FactoryBot.create(:post, user: User.first), it would create a post associated with the first user, but still create a new record. So, I get this:

irb(main):001:0> User.count
=> 1
irb(main:002:0> FactoryBot.create(:post, user: User.first)
=> #<Post id: 1, title: 'Lorem Ipsum', host_id: 1>
irb(main:003:0> User.count
=> 2

Everything works, it just creates a new user record that isn't attached to anything. Is there anyway to stop that from happening?

1 Answers

You don't need to tell FactoryBot to create(:user). Just remove it.

factory :post do
  user
  title { Faker::Lorem.sentence }
end

https://devhints.io/factory_bot

Related