Rspec and Factory girl

Factory_girl allows you to quickly define prototypes for each of your models and ask for instances with properties that are important to the test at hand.

This is one of the best ways to replace fixtures and help us write better specs for the applications.Factory girl is available as a gem and aslo as a plugin

gem install thoughtbot-factory_girl --source


git clone git://

Factories can be created anywhere.They will be automatically loaded if they are defined in test or spec folders.

We can create a basic factory like this

Factory.define :user do |u| “mokeydevel” “”


This created factory can be called using Factory.create or

When we say Factory.create it would create a query in the sql while build creates a factory in memory.

When using factory girl with rspec it would look soemthing like this,

describe “User”, :model=>”User” do

before(:each) do

@person = Factory.create(:user)


it ” Should be a new record “do

@person.should  be_new_record



We can also user Faker gem to create fake data.When we user faker gem a factory would look like this

Factory.define :user do |u|


@person = Factory.create(:user,:name=>”monkey”,:email=>”’)


, ,

  1. Leave a comment

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: