Factory Girl and the Builder Pattern


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}"}

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

These factories can be used like so:

@user = FactoryGirl.create(:user)

Factory Girl gem

Like Factory Girl, we have others gems with the same purpose:

  1. Foundry (http://github.com/jeremymcanally/foundry/tree/master)
  2. Machinist (http://github.com/notahat/machinist)
  3. ObjectDaddy (http://tasks.ogtastic.com/projects/show/object-daddy)

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.

Bricks  is a hybrid gem with an Object Builder/Factory implementation.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s