Machinery to create object graphs and speed up tests

June 8, 2009

Machinery helps to create object graphs for use in tests without needing fixtures, using pure ruby style. These object graphs are easily re-usable in Test::Unit, RSpec, Cucumber and in rake tasks to populate a database.

Secondly, even if you don't need object graphs, Machinery can speed up your tests significantly because you can set up any model objects in a before(:all) instead of a before(:each), and at the end of the tests all activerecord objects created in the before(:all) will be cleaned up automatically.

Usage

In /spec/scenarios.rb

Machinery.define do
  scenario :earth_ships do
    @titanic = Ship.create!(:name => "Titanic")
    @pirate  = Ship.create!(:name => "Pirate")
  end

  scenario :space_ships do
    @apollo = Ship.create!(:name => "Apollo")
    @uss_enterprise = Ship.create!(:name => "USS Enterprise")
  end

  scenario :all_ships do
    scenarios :earth_ships, :space_ships
    @sunken_ship = Ship.create!(:name => "Sunk")
  end
end

In /spec/spec_helper.rb

require 'machinery'
require File.join(File.dirname(__FILE__) + 'scenarios')

In /spec/models/ship_spec.rb

describe Ship do
  scenarios :all_ships

  it "should create a pirate ship" do
    @pirate.should_not be_nil
  end

  it "should have 5 ships" do
    Ship.count.should == 5
  end
end

If it's only speeding up your tests you're after you can use anonymous scenarios, like this:

In /spec/models/ship_spec.rb

describe Ship do
  scenario do
    @pirate = Ship.create!(:name => "Pirate")
  end

  it "should update a pirate ship" do
    @pirate.name = "Updated Pirate"
    @pirate.save
    @pirate.reload
    @pirate.name.should == "Updated Pirate"
  end

  it "should have 1 ship" do
    Ship.count.should == 1
  end

  it "should be named 'Pirate'" do
    @pirate.name.should == "Pirate"
  end
end

This will create one ship only in the database.

Get it

For more info see http://github.com/lawrencepit/machinery.


Comments

  1. Your wheel looks familiar
    http://github.com/lachie/hornsby/tree/master

    Lachie Cox on June 9, 2009 at 1:23 am

  2. Hey Lachie, you're right, I did take inspiration for the use of instance variables from Hornsby, added you properly to the credits. Machinery does work in a completely different way though.

    — Lawrence Pit on June 9, 2009 at 2:40 am

  3. Have you seen http://github.com/aiwilliams/dataset/tree/master ?

    Jim Gay on June 9, 2009 at 4:32 pm

Leave a comment