Friday, March 14, 2008

Some rspec love for acts_as_state_machine

So I've once again revisited the almighty "acts_as_state_machine" plugin (http://elitists.textdriven.com/svn/plugins/acts_as_state_machine). Its really helpful, but one thing I've never liked is testing the valid transitions. Because, really you should test a whole lot of stuff; Enter :describe_valid_event_transitions.


class MyStatedObject < ActiveRecord::Base
acts_as_state_machine :initial => :pending, :column => 'status'
state :pending
state :active
state :completed
state :rejected

event :approve! do
transitions :to => :active, :from => :pending
end

event :reject! do
transitions :to => :rejected, :from => :pending
end
event :complete! do
transitions :to => :completed, :from => :active
end
end

describe MyStatedObject do
describe_valid_event_transitions do |transition|
transition.is_valid(:event => :approve!, :from => :pending, :to => :active)
transition.is_valid(:event => :reject!, :from => :pending, :to => :rejected)
transition.is_valid(:event => :complete!, :from => :active, :to => :completed)
end
end


Using the above code it will generate 3 (events) * 4 (statuses) * 4 (statuses) specs. If I were to inadvertently add a validator for :event => :stupify!, then the number of specs would be 4 * 4 * 4, and there would be a whole lot of failures.



module Spec
module Rails
module Matchers
# Specifies a valid state change
#
# options
# :from: The from state
# :to: The desired state
# :via: The event to fire the transition
def change_state(*args)
options = args.extract_options!
from_status = options[:from]
to_status = options[:to]
via_event = options[:via]
return simple_matcher("model should change status from :#{from_status} to :#{to_status} via :#{via_event} event") do |klass|
object = klass.is_a?(Class) ? klass.new : klass
object.stub!(:current_state).and_return(from_status.to_sym)
object.stub!(:status).and_return(from_status.to_s)
if event = object.next_states_for_event(via_event).detect{|event| event.to == to_status}
event.to.to_sym == to_status.to_sym
else
false
end
end
end
end
end
end


class Spec::Rails::Example::RailsExampleGroup

class ValidTransitionCollector #:nodoc:

def events
transition_table.collect{|t| t[:event]}.uniq
end

def states
transition_table.collect{|t| [t[:to], t[:from]]}.flatten.uniq
end

def add(options = {})
options.symbolize_keys!
transition_table << {:event => (options[:event] || options[:via]).to_sym, :from => options[:from].to_sym, :to => options[:to].to_sym}
end
alias_method :is_valid, :add

def has?(event, from, to)
transition_table.detect{|o| o[:event] == event && o[:from] == from && o[:to] == to}
end
protected
def transition_table
@transition_table ||= []
end
end

class << self
# This method assumes the use of the awesome acts_as_state_machine,
#
# Given all events (both defined and proposed to the validator)
# and all statuses (both defined and proposed to the validator),
# this method will iterate over the events, and then over
# the statuses as the "from" status, and then over the
# statuses again as the "to" status.
#
# With the event, from status and to status, this method
# will check against the validator to say it should or
# should_not state_change
#
#
# Usage:
#
# describe MyStatedObject do
# describe_valid_event_transitions do |transition|
# transition.is_valid(:event => :approve!, :from => :pending, :to => :active)
# transition.is_valid(:event => :reject!, :from => :pending, :to => :rejected)
# transition.is_valid(:event => :complete!, :from => :active, :to => :completed)
# end
# end
#
def describe_valid_event_transitions
collector = ValidTransitionCollector.new
yield(collector)
klass = description.constantize
describe 'status changes' do
(klass.event_table.keys + collector.events).uniq.each do |event|
(klass.states + collector.states).each do |possible_from_state|
(klass.states + collector.states).each do |possible_to_state|
should_transition = false
if result = collector.has?(event, possible_from_state, possible_to_state)
should_transition = true
end

it "should #{should_transition ? '' : 'NOT '}change from :#{possible_from_state} to :#{possible_to_state} via :#{event}" do
klass.send("#{should_transition ? 'should' : 'should_not'}", change_state(:via => event, :from => possible_from_state, :to => possible_to_state))
end
end
end
end
end
end
end
end

Thursday, January 24, 2008

RSpec Delegation Assertion

So I've made the jump to using RSpec, and I love it. I really like the declarative nature of the matchers, and feel compelled to write useful ones. Below is a matcher for testing delegations. As of right now, I have not yet decided if I should have the
matcher be at the class level or the object level. We'll see. Perhaps iteration 2.


class Comment < ActiveRecord::Base
extend Forwardable
belongs_to :user
def_delegator :user, :name, :author_name
end

describe Comment do
it 'should delegate author_name to user' do
Comment.should delegate(:author_name, :to => :user, :via => :name)
end
end

Below is a helpful tester for delegations, inspired by Jay Fields, and more importantly made possible by Obie Fernandez's most excellent The Rails Way.

module Spec
module Rails
module Matchers
# describe Comment do
# it 'should delegate author_name to user' do
# Comment.should delegate(:author_name, :to => :user, :via => :name)
# end
# end
class Delegation
private
attr_reader :expected, :actual, :method_name, :options, :to, :via
public
def initialize(method_name, options = {})
@method_name = method_name
options.symbolize_keys!
@to = options[:to]
@via = options[:via] || method_name
end

def matches?(klass)
@actual = klass
delegate_class = Class.new
delegate_class.send(:attr_accessor, @via)

delegate_object = delegate_class.new
delegate_object.send("#{@via}=", :spec_rails_matchers_delegation)

@base_object = @actual.new

# Use the singleton class of the base_object
# I am rewriting the @to method on the base_object's meta_class
# but not altering the base_object's parent class
# So if I instantiate another instance of @actual
# it will not have the below behavior, only the @base_object will
#
# http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html
singleton = @base_object.instance_eval("class << self; self; end")
singleton.class_eval("attr_accessor :#{@to}")

@base_object.send("#{@to}=", delegate_object)
@base_object.send(method_name) == :spec_rails_matchers_delegation
end

def failure_message
"expected #{actual.to_s} to delegate :#{method_name} to :#{to} via :#{via}"
end

def negative_failure_message
"expected #{actual.to_s} to NOT delegate :#{method_name} to :#{to} via :#{via}"
end

def to_s
"#{actual.to_s} delegates :#{method_name} to :#{to} via :#{via}"
end

end
def delegates(method_name, options = {})
Delegation.new(method_name, options)
end
alias_method :delegate, :delegates
end
end
end

Monday, August 27, 2007

Ruby UML Diagrammer

Well, after a few bursts of creativity, I've finally posted the Ruby UML Diagrammer (http://rumld.rubyforge.org/)


$ sudo gem install rumld --included-dependencies
$ rumld --help

Wednesday, August 08, 2007

Digging for method signatures

This evening I decided to write some UML for the permission sub-system that I'd been working on. I decided that I really should have it in dot format because 1) I want to learn it better, 2) its plain text and thus more "Pragmatic", 3) there are rails gems (i.e. railroad) that can generate dot format. So I wrote the dot file (with inspiration from a railroad output). During the process, I decided to include the method signatures, which definitely helps to explain what's going on.

Then, I decided that I'd really like my classes to be able to generate this UML (in particular I wanted the method signature). So with a little thinking, I started to roll my own, but it gets a bit complicated parsing the source file and determining what's going on. Fortunately, after 30 minutes, I realized that RDoc does the hard-work for me, and all I need to do is parse the html.

Enter RdocInspector. It takes a string and finds and collects the Public Class methods, Public Instance methods, and Protected Instance methods (as well as their arguements). The string is the result of File.read(some_rdoc_html_file).

My UML automation work is not yet done, but the issue of what methods are explicitly defined in a given file has been solved.

Wednesday, July 18, 2007

Mocha

So my previous post talked about overriding delegation. Then I remembered, Mocha. An honest to goodness stubbing/mocking library. Rather obviously, when testing units, I really don't want to fiddle around with the interaction of objects in each and every instance.

So instead of my convoluted example of conditionally_overriding_delegation, I can do the following (but hey you may have already known this):


class AbstractUnit
extend Forwardable
def_delegate :foo, :name

def has_name?
!(name.nil? || name.blank?)
end
end

class AbstractUnitTest < Test::Unit::TestCase
def setup
@object = AbstractUnit.new
end

# Perhaps a reasonable test for delegation?
def test_should_delegate_name_to_foo
assert_equal @object.name, @object.foo.name
end

def test_has_name_should_be_false_if_name_is_empty
@object.stubs(:name).returns('')
assert ! @object.has_name?
end

def test_has_name_should_be_false_if_name_is_nil
@object.stubs(:name).returns(nil)
assert ! @object.has_name?
end

def test_has_name_should_be_false_if_name_is_blank
@object.stubs(:name).returns('hello world')
assert @object.has_name?
end

end


Even in this case, Mocha is rather useful, I don't have to worry about testing the coupling that occurs due to delegation, and can test the objects responsibilities. Of course, now its time to look more into Mocha's documentation. It looks like there is some rather amazing stuff that can be done.