From 5a8454221f0352aba37115c491220e016ea78872 Mon Sep 17 00:00:00 2001 From: Luke Roberts Date: Sun, 1 Mar 2015 20:08:45 -0800 Subject: [PATCH] reference state machine object and event in invalid transition error so end user can intelligently handle --- lib/aasm/aasm.rb | 2 +- lib/aasm/errors.rb | 13 ++++++++++++- spec/unit/transition_spec.rb | 7 ++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/aasm/aasm.rb b/lib/aasm/aasm.rb index 942f5dd..59d26fa 100644 --- a/lib/aasm/aasm.rb +++ b/lib/aasm/aasm.rb @@ -129,7 +129,7 @@ private end if AASM::StateMachine[self.class].config.whiny_transitions - raise AASM::InvalidTransition, "Event '#{event_name}' cannot transition from '#{aasm.current_state}'" + raise AASM::InvalidTransition.new(self, event_name) else false end diff --git a/lib/aasm/errors.rb b/lib/aasm/errors.rb index 9b975d0..7e36fd8 100644 --- a/lib/aasm/errors.rb +++ b/lib/aasm/errors.rb @@ -1,5 +1,16 @@ module AASM - class InvalidTransition < RuntimeError; end + + class InvalidTransition < RuntimeError + attr_reader :object, :event_name + def initialize(object, event_name) + @object, @event_name = object, event_name + end + + def message + "Event '#{event_name}' cannot transition from '#{object.aasm.current_state}'" + end + end + class UndefinedState < RuntimeError; end class NoDirectAssignmentError < RuntimeError; end end diff --git a/spec/unit/transition_spec.rb b/spec/unit/transition_spec.rb index 12e70de..6d9194c 100644 --- a/spec/unit/transition_spec.rb +++ b/spec/unit/transition_spec.rb @@ -4,7 +4,12 @@ describe 'transitions' do it 'should raise an exception when whiny' do process = ProcessWithNewDsl.new - expect { process.stop! }.to raise_error(AASM::InvalidTransition) + expect { process.stop! }.to raise_error do |err| + expect(err.class).to eql(AASM::InvalidTransition) + expect(err.message).to eql("Event 'stop' cannot transition from 'sleeping'") + expect(err.object).to eql(process) + expect(err.event_name).to eql(:stop) + end expect(process).to be_sleeping end