Defining Factories

suggest change

For an Active Record User with name and email, FactoryGirl can guess the class:

FactoryGirl.define do
  factory :user do # guesses the User class
    name  "John"
    email "john@example.com"
  end
end

Or name the factory and set the class yourself:

FactoryGirl.define do
  factory :user_jack, class: User do
    name  "Jack"
    email "jack@example.com"
  end
end

In a spec:

build(:user)      # unsaved User filled with John's data
build(:user_jack) # unsaved User filled with Jack's data

The common methods are:

user = build(:user)          # unsaved instance
user = create(:user)         # saved instance
attrs = attributes_for(:user) # hash of attributes, not a User

FactoryBot 5 and later does not accept the bare name "John" form. Wrap static values in a block: name { "John" }. The gem was renamed from FactoryGirl to FactoryBot.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents