Factory Girl and the Builder Pattern

Standard

You want to test your code, for example, you will do an Integration Test. At each time We will really create our objects?
Using factories, you will define it just once. With this in mind, you can have focus on test. We want keep focusing on our tests. Factory Girl is widely used and implements the Factory Pattern.

FactoryGirl.define do
factory :user do
sequence(:name) {|n| "Name_#{n}"}
sequence(:email) {|n| "Name_#{n}@email.com"}
sequence(:password) {|n| "password_#{n}"}
end
end
# Let's define a sequence that factories can use. This sequence defines a
# unique e-mail address. The first address will be "somebody1@example.com",
# and the second will be "somebody2@example.com."
Factory.sequence :email do |n|
"somebody#{n}@example.com"
end

With the Factory Pattern we can create several different but related kinds of objects in one step. But if You cannot create a lot of objects in a single step,maybe You will use the Builder Pattern. The Factoy Pattern can be seen as a simplified version of the Builder pattern. The Builder Pattern isn’t used in Ruby On Rails.