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 http://gems.github.com

or

git clone git://github.com/thoughtbot/factory_girl.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|

u.name “mokeydevel”

u.email “test@test.com”

end

This created factory can be called using Factory.create or Factory.build

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)

end

it ” Should be a new record “do

@person.should  be_new_record

end

end

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|

u.name Faker::Name.name

u.email Faker::Internet.email

end

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

Advertisements

, ,

  1. Leave a comment

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 )

w

Connecting to %s

%d bloggers like this: