public
Description: A simple object factory that assists with creating valid model objects when writing specifications
Home | Edit | New

Usage with Rails, RSpec and Cucumber

This is how we have things set up for our Rails projects (with RSpec and Cucumber goodness).

Currently (as of version 0.1.3) there is a bug when ObjectFactory is used as a gem – so we install it as a plugin (cd vendor/plugins && gem unpack brightbox-object-factory does the trick). However, I promise I will get this fixed very soon.

Preparation

We add a setup file to the lib folder: lib/prepare_object_factory.rb.

This contains a function that prepares the ObjectFactory for use:


def prepare_object_factory
  when_creating_a Company, 
    :auto_generate => [:name, :address, :city, :postcode, :telephone]

  when_creating_a Person, 
    :auto_generate => [:first_name, :last_name], 
    :auto_confirm => :password, 
    :generate_email_address => :email, 
    :set => { :age => 22 }, 
    :generate => { :company => lambda { a_saved Company } }
end

Note the use of :generate and lambda to ensure that people are linked to a (dynamically created) Company (unless you explicitly override it at creation-time).

RSpec

We then add the following to our spec/spec_helper.rb


require 'object_factory'
require 'lib/prepare_object_factory'

Spec::Runner.configure do |config|
  # various bits of config
  config.before :all do 
    prepare_object_factory
  end
end

This makes sure that the factory is prepared before running the specs.

You can then use it in your specs as follows:


describe Person do
  it "should have a first name" do
    @person = a Person, :first_name => ''
    @person.should_not be_valid
    @person.should have(1).errors_on(:first_name)
  end
  it "should belong to a company" do
    @person = a Person, :company => nil
    @person.should_not be_valid
    @person.should have(1).errors_on(:company)
  end
  # und so weiter
end

Cucumber

We add the following to features/support/env.rb:


require 'object_factory'
require 'lib/prepare_object_factory'

prepare_object_factory

And we use it in our steps as follows:


Given /^someone called (.*)$/ do | first_name | 
  person = a_saved Person, :first_name => first_name
end

Pretty simple huh?

Last edited by rahoulb, Thu Mar 05 13:22:15 -0800 2009
Home | Edit | New
Versions: