Search code examples
ruby-on-railsrubyrspecfactory-bot

How to specify the association with factory_bot?


For example I have two models a user and a post. A post belongs_to a user and a user has many posts

#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

Using Rspec in a test I want to do this:

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

I would expect that the user_id of post to be 1 however it is creating another user prior and the user_id is 2.

How can you specify the association when you are creating the object with factory_bot / factory_girl?


Solution

  • Update Dec 2023

    The FactoryBot association can be specified in both explicit and implicit associations. At least from version factory_bot-6.2.0

    Original response

    You should use explicit associations instead of implicit ones:

    #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#associations