Thursday, January 03, 2013

Rails 3.2, Factory Girl


1. Include :
 
    group :development, :test do
 gem 'factory_girl_rails'
end

in Gemfile

2. bundle install
3. create factories.rb under spec folder
4. Add the factory definitions in it :

FactoryGirl.define do
 factory :user do
   email 'elinora@zepho.com'
   password 'welcome'
   primary_paypal_email 'elinora.price@zepho.com'
 end
 # product factory with a belongs_to association for the user
 factory :product do
   name 'TDD Workbook'
   price 49.99
   user
   thanks_page 'www.zepho.com/thanks.html'
   cancel_page 'www.zepho.com/cancel.html'
   sales_page 'www.zepho.com/sales_page.html'
   download_page 'www.zepho.com/download.html'  
 end
end

In this definition I have factory for user has_many :products relationship.
5. Create a support directory and include controller_macros.rb in it:
module ControllerMacros
 def login_user
   @request.env["devise.mapping"] = Devise.mappings[:user]
   user = FactoryGirl.create(:user)
   # user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
   sign_in user
 end
end
6. In spec_helper.rb add the devise helpers:
RSpec.configure do |config|
 ...
 config.include Devise::TestHelpers, :type => :controller
 config.include ControllerMacros, :type => :controller
 ...
end
7. In your controller spec, now you can do this:
 
   context 'User is logged in' do
    before do
      login_user
    end

    it 'should render index page' do
      get :index

      response.should be_success
    end
  end