Skip to content

Instantly share code, notes, and snippets.

@kennethkalmer
Created October 7, 2009 17:12
Show Gist options
  • Save kennethkalmer/204224 to your computer and use it in GitHub Desktop.
Save kennethkalmer/204224 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'activerecord'
$:.unshift('lib')
require 'state_machine'
ActiveRecord::Base.establish_connection({
:adapter => 'mysql',
:database => 'test',
:username => 'root'
})
ActiveRecord::Base.connection.execute "DROP TABLE IF EXISTS foos"
ActiveRecord::Base.connection.execute <<EOSQL
CREATE TABLE foos (
id INT NOT NULL AUTO_INCREMENT,
state VARCHAR(255),
string VARCHAR(255),
PRIMARY KEY (id)
);
EOSQL
class Foo < ActiveRecord::Base
attr_reader :changes_before_update, :changes_before_save
state_machine :initial => 'park' do
event :ignite do
transition :park => :idling
end
event :park do
transition :idling => :park
end
end
def before_save
@changes_before_save = changes
end
def before_update
@changes_before_update = changes
end
end
require 'test/unit'
class AttributeTest < Test::Unit::TestCase
def setup
Foo.delete_all
end
def test_initial
foo = Foo.new( :string => 'arb' )
foo.save
expected = { 'state' => [ nil, 'park' ], 'string' => [ nil, 'arb' ] }
assert_equal expected, foo.changes_before_save
end
def test_changes
foo = Foo.new
foo.save
foo.update_attribute :string, 'arb'
expected = { "string" => [ nil, "arb" ] }
assert_equal expected, foo.changes_before_update
foo.ignite!
expected = { "state" => [ 'park', 'idling' ] }
assert_equal expected, foo.changes_before_update
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment