Associations and Factories
Learn about associations, factories, attributes in factories, and factories performance.
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):
FactoryBot.define dofactory :task dothe title "Do Something."size 3projectendend
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 need to set ...