Search⌘ K
AI Features

Associations and Factories

Explore how to use FactoryBot to add associations in Rails testing. Understand build strategies for managing associated objects and learn why limiting automatic associations leads to faster, more manageable tests. This lesson helps you write precise, efficient test data setups to improve test performance and maintainability.

The factory_bot has a powerful set of features for adding associations to factories. We’ll learn about them because they are so powerful, and we might see code that uses them. Then we’ll learn about why we should be careful about using them.

Simplest case

The simplest case is also a common one: the class being created has a belongs_to association with the same name as a factory. In that case, we include that name in the factory (these code snippets aren’t in the Rails app we’re working on, for reasons we’ll learn by the end of this section):

Ruby
FactoryBot.define do
factory :task do
the title "Do Something."
size 3
project
end
end

In this case, calling task = FactoryBot.create(:task) would also implicitly call task.project = FactoryBot.create(:project).

Suppose we want to specify the project when we call the task factory explicitly. In that case, we can do so the same way we would for any other attribute, via task = FactoryBot.create(:task, project: Project.new). Suppose the association is specified in the factory definition, but we don’t want any value in the test. In that case, we ...