repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/work.rb
spec/models/active_record/work.rb
class Work < ActiveRecord::Base include AASM end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/transient.rb
spec/models/active_record/transient.rb
class Transient < ActiveRecord::Base def aasm_write_state_without_persistence(state) "fum" end include AASM end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/worker.rb
spec/models/active_record/worker.rb
class Worker < ActiveRecord::Base end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/simple_new_dsl.rb
spec/models/active_record/simple_new_dsl.rb
class SimpleNewDsl < ActiveRecord::Base include AASM aasm :column => :status aasm do state :unknown_scope, :another_unknown_scope state :new end end class MultipleSimpleNewDsl < ActiveRecord::Base include AASM aasm :left, :column => :status aasm :left do state :unknown_scope, :another_unknown_scope state :new end end class AbstractClassDsl < ActiveRecord::Base include AASM self.abstract_class = true aasm :column => :status aasm do state :unknown_scope, :another_unknown_scope state :new end end class ImplementedAbstractClassDsl < AbstractClassDsl end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/localizer_test_model.rb
spec/models/active_record/localizer_test_model.rb
class LocalizerTestModel < ActiveRecord::Base include AASM aasm do state :opened, :initial => true state :closed event :close event :open end end describe 'localized state names' do before(:all) do I18n.load_path << 'spec/localizer_test_model_new_style.yml' I18n.reload! end after(:all) do I18n.load_path.delete('spec/localizer_test_model_new_style.yml') I18n.backend.load_translations end it 'should localize' do state = LocalizerTestModel.aasm.states.detect {|s| s == :opened} expect(state.localized_name).to eq("It's open now!") expect(state.human_name).to eq("It's open now!") expect(state.display_name).to eq("It's open now!") I18n.with_locale(:fr) do expect(state.localized_name).to eq("C'est ouvert maintenant!") expect(state.human_name).to eq("C'est ouvert maintenant!") expect(state.display_name).to eq("C'est ouvert maintenant!") end end it 'should use fallback' do state = LocalizerTestModel.aasm.states.detect {|s| s == :closed} expect(state.localized_name).to eq('Closed') expect(state.human_name).to eq('Closed') expect(state.display_name).to eq('Closed') end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/basic_active_record_two_state_machines_example.rb
spec/models/active_record/basic_active_record_two_state_machines_example.rb
class BasicActiveRecordTwoStateMachinesExample < ActiveRecord::Base include AASM aasm :search do state :initialised, :initial => true state :queried state :requested event :query do transitions :from => [:initialised, :requested], :to => :queried end event :request do transitions :from => :queried, :to => :requested end end aasm :sync do state :unsynced, :initial => true state :synced event :synchronise do transitions :from => :unsynced, :to => :synced end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/gate.rb
spec/models/active_record/gate.rb
class Gate < ActiveRecord::Base include AASM # Fake this column for testing purposes # attr_accessor :aasm_state def value 'value' end aasm do state :opened state :closed event :view do transitions :to => :read, :from => [:needs_attention] end end end class MultipleGate < ActiveRecord::Base include AASM # Fake this column for testing purposes # attr_accessor :aasm_state def value 'value' end aasm :left, :column => :aasm_state do state :opened state :closed event :view do transitions :to => :read, :from => [:needs_attention] end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/person.rb
spec/models/active_record/person.rb
class Base < ActiveRecord::Base include AASM aasm column: 'status' do state :inactive, initial: true state :active event :activate do transitions from: :inactive, to: :active end event :deactivate do transitions from: :active, to: :inactive end end self.abstract_class = true self.table_name = 'users' end class Person < Base end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/active_record/with_enum_without_column.rb
spec/models/active_record/with_enum_without_column.rb
class WithEnumWithoutColumn < ActiveRecord::Base include AASM if ActiveRecord::VERSION::MAJOR >= 4 && ActiveRecord::VERSION::MINOR >= 1 # won't work with Rails <= 4.1 enum status: { opened: 0, closed: 1 } end aasm :column => :status do state :closed, initial: true state :opened event :view do transitions :to => :opened, :from => :closed end end end class MultipleWithEnumWithoutColumn < ActiveRecord::Base include AASM if ActiveRecord::VERSION::MAJOR >= 4 && ActiveRecord::VERSION::MINOR >= 1 # won't work with Rails <= 4.1 enum status: { opened: 0, closed: 1 } end aasm :left, :column => :status do state :closed, initial: true state :opened event :view do transitions :to => :opened, :from => :closed end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/generators/mongoid_generator_spec.rb
spec/generators/mongoid_generator_spec.rb
require 'spec_helper' if defined?(Mongoid::Document) require 'generator_spec' require 'generators/mongoid/aasm_generator' describe Mongoid::Generators::AASMGenerator, type: :generator do destination File.expand_path("../../../tmp", __FILE__) before(:all) do prepare_destination end it "creates model with aasm block for default column_name" do run_generator %w(user) assert_file "app/models/user.rb", /include AASM\n\n aasm do\n end\n/ end it "creates model with aasm block for custom column_name" do run_generator %w(user state) assert_file "app/models/user.rb", /aasm :column => 'state' do\n end\n/ end it "creates model with aasm block for namespaced model" do run_generator %w(Admin::User state) assert_file "app/models/admin/user.rb", /aasm :column => 'state' do\n end\n/ end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/generators/active_record_generator_spec.rb
spec/generators/active_record_generator_spec.rb
require 'spec_helper' if defined?(ActiveRecord) require 'generator_spec' require 'generators/active_record/aasm_generator' describe ActiveRecord::Generators::AASMGenerator, type: :generator do destination File.expand_path("../../../tmp", __FILE__) before(:all) do prepare_destination end it "creates model with aasm block for default column_name" do run_generator %w(user) assert_file "app/models/user.rb", /include AASM\n\n aasm do\n end\n/ end it "creates model with aasm block for custom column_name" do run_generator %w(user state) assert_file "app/models/user.rb", /aasm :column => 'state' do\n end\n/ end it "creates model with aasm block for namespaced model" do run_generator %w(Admin::User state) assert_file "app/models/admin/user.rb", /aasm :column => 'state' do\n end\n/ end it "creates migration for model with aasm_column" do run_generator %w(post) assert_migration "db/migrate/aasm_create_posts.rb", /create_table(:posts) do |t|\n t.string :aasm_state\n/ end it "add aasm_column in existing model" do run_generator %w(job) assert_file "app/models/job.rb" run_generator %w(job) assert_migration "db/migrate/add_aasm_state_to_jobs.rb" end it "add custom aasm_column in existing model" do run_generator %w(job state) assert_migration "db/migrate/add_state_to_jobs.rb" end it "dont add column if column is already exists" do require 'models/active_record/work.rb' load_schema run_generator %w(work status) assert_no_migration "db/migrate/add_status_to_jobs.rb" end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/generators/no_brainer_generator_spec.rb
spec/generators/no_brainer_generator_spec.rb
require 'spec_helper' if defined?(NoBrainer::Document) require 'generator_spec' require 'generators/nobrainer/aasm_generator' describe NoBrainer::Generators::AASMGenerator, type: :generator do destination File.expand_path('../../../tmp', __FILE__) before(:all) do prepare_destination end it 'creates model with aasm block for default column_name' do run_generator %w[user] assert_file 'app/models/user.rb', /include AASM\n\n aasm do\n end\n/ end it 'creates model with aasm block for custom column_name' do run_generator %w[user state] assert_file 'app/models/user.rb', /aasm :column => 'state' do\n end\n/ end it 'creates model with aasm block for namespaced model' do run_generator %w[Admin::User state] assert_file 'app/models/admin/user.rb', /aasm :column => 'state' do\n end\n/ end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/inspection_multiple_spec.rb
spec/unit/inspection_multiple_spec.rb
require 'spec_helper' describe 'inspection for common cases' do it 'should support the new DSL' do # 1st state machine expect(FooMultiple.aasm(:left)).to respond_to(:states) expect(FooMultiple.aasm(:left).states.size).to eql 3 expect(FooMultiple.aasm(:left).states).to include(:open) expect(FooMultiple.aasm(:left).states).to include(:closed) expect(FooMultiple.aasm(:left).states).to include(:final) expect(FooMultiple.aasm(:left)).to respond_to(:initial_state) expect(FooMultiple.aasm(:left).initial_state).to eq(:open) expect(FooMultiple.aasm(:left)).to respond_to(:events) expect(FooMultiple.aasm(:left).events.size).to eql 2 expect(FooMultiple.aasm(:left).events).to include(:close) expect(FooMultiple.aasm(:left).events).to include(:null) # 2nd state machine expect(FooMultiple.aasm(:right)).to respond_to(:states) expect(FooMultiple.aasm(:right).states.size).to eql 3 expect(FooMultiple.aasm(:right).states).to include(:green) expect(FooMultiple.aasm(:right).states).to include(:yellow) expect(FooMultiple.aasm(:right).states).to include(:red) expect(FooMultiple.aasm(:right)).to respond_to(:initial_state) expect(FooMultiple.aasm(:right).initial_state).to eq(:green) expect(FooMultiple.aasm(:right)).to respond_to(:events) expect(FooMultiple.aasm(:right).events.size).to eql 3 expect(FooMultiple.aasm(:right).events).to include(:green) expect(FooMultiple.aasm(:right).events).to include(:yellow) expect(FooMultiple.aasm(:right).events).to include(:red) end context "instance level inspection" do let(:foo) { FooMultiple.new } let(:two) { FooTwoMultiple.new } it "delivers all states" do # 1st state machine states = foo.aasm(:left).states expect(states.size).to eql 3 expect(states).to include(:open) expect(states).to include(:closed) expect(states).to include(:final) states = foo.aasm(:left).states(:permitted => true) expect(states.size).to eql 1 expect(states).to include(:closed) expect(states).not_to include(:open) expect(states).not_to include(:final) foo.close expect(foo.aasm(:left).states(:permitted => true)).to be_empty # 2nd state machine states = foo.aasm(:right).states expect(states.size).to eql 3 expect(states).to include(:green) expect(states).to include(:yellow) expect(states).to include(:red) states = foo.aasm(:right).states(:permitted => true) expect(states.size).to eql 1 expect(states).to include(:yellow) expect(states).not_to include(:green) expect(states).not_to include(:red) foo.yellow states = foo.aasm(:right).states(:permitted => true) expect(states.size).to eql 2 expect(states).to include(:red) expect(states).to include(:green) expect(states).not_to include(:yellow) end it "delivers all states for subclasses" do # 1st state machine states = two.aasm(:left).states expect(states.size).to eql 4 expect(states).to include(:open) expect(states).to include(:closed) expect(states).to include(:final) expect(states).to include(:foo) states = two.aasm(:left).states(:permitted => true) expect(states.size).to eql 1 expect(states).to include(:closed) expect(states).not_to include(:open) two.close expect(two.aasm(:left).states(:permitted => true)).to be_empty # 2nd state machine states = two.aasm(:right).states expect(states.size).to eql 4 expect(states).to include(:green) expect(states).to include(:yellow) expect(states).to include(:red) expect(states).to include(:bar) states = two.aasm(:right).states(:permitted => true) expect(states.size).to eql 1 expect(states).to include(:yellow) expect(states).not_to include(:red) expect(states).not_to include(:green) expect(states).not_to include(:bar) two.yellow states = two.aasm(:right).states(:permitted => true) expect(states.size).to eql 2 expect(states).to include(:green) expect(states).to include(:red) expect(states).not_to include(:yellow) expect(states).not_to include(:bar) end it "delivers all events" do # 1st state machine events = foo.aasm(:left).events expect(events.size).to eql 2 expect(events).to include(:close) expect(events).to include(:null) foo.close expect(foo.aasm(:left).events).to be_empty # 2nd state machine events = foo.aasm(:right).events expect(events.size).to eql 1 expect(events).to include(:yellow) expect(events).not_to include(:green) expect(events).not_to include(:red) foo.yellow events = foo.aasm(:right).events expect(events.size).to eql 2 expect(events).to include(:green) expect(events).to include(:red) expect(events).not_to include(:yellow) end end it 'should list states in the order they have been defined' do expect(ConversationMultiple.aasm(:left).states).to eq([ :needs_attention, :read, :closed, :awaiting_response, :junk ]) end end describe "special cases" do it "should support valid as state name" do expect(ValidStateNameMultiple.aasm(:left).states).to include(:invalid) expect(ValidStateNameMultiple.aasm(:left).states).to include(:valid) argument = ValidStateNameMultiple.new expect(argument.invalid?).to be_truthy expect(argument.aasm(:left).current_state).to eq(:invalid) argument.valid! expect(argument.valid?).to be_truthy expect(argument.aasm(:left).current_state).to eq(:valid) end end describe 'aasm.states_for_select' do context 'without I18n' do before { allow(Module).to receive(:const_defined?).with(:I18n).and_return(nil) } it "should return a select friendly array of states" do expect(FooMultiple.aasm(:left)).to respond_to(:states_for_select) expect(FooMultiple.aasm(:left).states_for_select).to eq( [['Open', 'open'], ['Closed', 'closed'], ['Final', 'final']] ) end end end describe 'aasm.from_states_for_state' do it "should return all from states for a state" do expect(ComplexExampleMultiple.aasm(:left)).to respond_to(:from_states_for_state) froms = ComplexExampleMultiple.aasm(:left).from_states_for_state(:active) [:pending, :passive, :suspended].each {|from| expect(froms).to include(from)} end it "should return from states for a state for a particular transition only" do froms = ComplexExampleMultiple.aasm(:left).from_states_for_state(:active, :transition => :left_unsuspend) [:suspended].each {|from| expect(froms).to include(from)} end end describe 'permitted events' do let(:foo) {FooMultiple.new} it 'work' do expect(foo.aasm(:left).events(:permitted => true)).to include(:close) expect(foo.aasm(:left).events(:permitted => true)).not_to include(:null) expect(foo.aasm(:right).events(:permitted => true)).to include(:yellow) expect(foo.aasm(:right).events(:permitted => true)).not_to include(:green) expect(foo.aasm(:right).events(:permitted => true)).not_to include(:red) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/inspection_spec.rb
spec/unit/inspection_spec.rb
require 'spec_helper' describe 'inspection for common cases' do it 'should support the new DSL' do expect(Foo.aasm).to respond_to(:states) expect(Foo.aasm.states).to include(:open) expect(Foo.aasm.states).to include(:closed) expect(Foo.aasm).to respond_to(:initial_state) expect(Foo.aasm.initial_state).to eq(:open) expect(Foo.aasm).to respond_to(:events) expect(Foo.aasm.events).to include(:close) expect(Foo.aasm.events).to include(:null) end context "instance level inspection" do let(:foo) { Foo.new } let(:two) { FooTwo.new } let(:multi) { MultiTransitioner.new } it "delivers all states" do states = foo.aasm.states expect(states).to include(:open) expect(states).to include(:closed) expect(states).to include(:final) permitted_states = foo.aasm.states(:permitted => true) expect(permitted_states).to include(:closed) expect(permitted_states).not_to include(:open) expect(permitted_states).not_to include(:final) blocked_states = foo.aasm.states(:permitted => false) expect(blocked_states).to include(:closed) expect(blocked_states).not_to include(:open) expect(blocked_states).to include(:final) foo.close expect(foo.aasm.states(:permitted => true)).to be_empty end it "delivers all states for subclasses" do states = two.aasm.states expect(states).to include(:open) expect(states).to include(:closed) expect(states).to include(:final) expect(states).to include(:foo) states = two.aasm.states(:permitted => true) expect(states).to include(:closed) expect(states).not_to include(:open) expect(states).not_to include(:final) two.close expect(two.aasm.states(:permitted => true)).to be_empty end it "delivers all events" do events = foo.aasm.events expect(events).to include(:close) expect(events).to include(:null) foo.close expect(foo.aasm.events).to be_empty end it "delivers permitted states when multiple transitions are defined" do multi.can_run = false states = multi.aasm.states(:permitted => true) expect(states).to_not include(:running) expect(states).to include(:dancing) multi.can_run = true states = multi.aasm.states(:permitted => true) expect(states).to include(:running) expect(states).to_not include(:dancing) end it "transitions to correct state if from state is missing from one transitions" do multi.sleep expect(multi.aasm.current_state).to eq(:sleeping) end end it 'should list states in the order they have been defined' do expect(Conversation.aasm.states).to eq([:needs_attention, :read, :closed, :awaiting_response, :junk]) end end describe "special cases" do it "should support valid as state name" do expect(ValidStateName.aasm.states).to include(:invalid) expect(ValidStateName.aasm.states).to include(:valid) argument = ValidStateName.new expect(argument.invalid?).to be_truthy expect(argument.aasm.current_state).to eq(:invalid) argument.valid! expect(argument.valid?).to be_truthy expect(argument.aasm.current_state).to eq(:valid) end end describe 'aasm.states_for_select' do context 'without I18n' do before { allow(Module).to receive(:const_defined?).with(:I18n).and_return(nil) } it "should return a select friendly array of states" do expect(Foo.aasm).to respond_to(:states_for_select) expect(Foo.aasm.states_for_select).to eq([['Open', 'open'], ['Closed', 'closed'], ['Final', 'final']]) end end end describe 'aasm.from_states_for_state' do it "should return all from states for a state" do expect(ComplexExample.aasm).to respond_to(:from_states_for_state) froms = ComplexExample.aasm.from_states_for_state(:active) [:pending, :passive, :suspended].each {|from| expect(froms).to include(from)} end it "should return from states for a state for a particular transition only" do froms = ComplexExample.aasm.from_states_for_state(:active, :transition => :unsuspend) [:suspended].each {|from| expect(froms).to include(from)} end end describe 'permitted events' do let(:foo) {Foo.new} it 'work' do expect(foo.aasm.events(:permitted => true)).to include(:close) expect(foo.aasm.events(:permitted => true)).not_to include(:null) end it 'should not include events in the reject option' do expect(foo.aasm.events(:permitted => true, reject: :close)).not_to include(:close) expect(foo.aasm.events(:permitted => true, reject: [:close])).not_to include(:close) end end describe 'not permitted events' do let(:foo) {Foo.new} it 'work' do expect(foo.aasm.events(:permitted => false)).to include(:null) expect(foo.aasm.events(:permitted => false)).not_to include(:close) end it 'should not include events in the reject option' do expect(foo.aasm.events(:permitted => false, reject: :null)).to eq([]) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/callback_multiple_spec.rb
spec/unit/callback_multiple_spec.rb
require 'spec_helper' Dir[File.dirname(__FILE__) + "/../models/callbacks/*.rb"].sort.each { |f| require File.expand_path(f) } describe 'callbacks for the new DSL' do it "be called in order" do show_debug_log = false callback = Callbacks::BasicMultiple.new(:log => show_debug_log) callback.aasm(:left).current_state unless show_debug_log expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered # these should be before the state changes expect(callback).to receive(:exit_open).once.ordered # expect(callback).to receive(:event_guard).once.ordered.and_return(true) # expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:after_transition).once.ordered expect(callback).to receive(:before_enter_closed).once.ordered expect(callback).to receive(:enter_closed).once.ordered expect(callback).to receive(:aasm_write_state).with(:closed, :left).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:after_exit_open).once.ordered # these should be after the state changes expect(callback).to receive(:after_enter_closed).once.ordered expect(callback).to receive(:after_event).once.ordered end # puts "------- close!" callback.left_close! end it "does not run any state callback if the event guard fails" do callback = Callbacks::BasicMultiple.new(:log => false) callback.aasm(:left).current_state expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(false) expect(callback).to_not receive(:transition_guard) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:after_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after_event) expect { callback.left_close! }.to raise_error(AASM::InvalidTransition, "Event 'left_close' cannot transition from 'open'. Failed callback(s): [:event_guard].") end it "handles private callback methods as well" do show_debug_log = false callback = Callbacks::PrivateMethodMultiple.new(:log => show_debug_log) callback.aasm(:left).current_state # puts "------- close!" expect { callback.close! }.to_not raise_error end context "if the transition guard fails" do it "does not run any state callback if guard is defined inline" do show_debug_log = false callback = Callbacks::BasicMultiple.new(:log => show_debug_log, :fail_transition_guard => true) callback.aasm(:left).current_state unless show_debug_log expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:after_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after_event) end expect { callback.left_close! }.to raise_error(AASM::InvalidTransition, "Event 'left_close' cannot transition from 'open'. Failed callback(s): [:transition_guard].") end it "does not run transition_guard twice for multiple permitted transitions" do show_debug_log = false callback = Callbacks::MultipleTransitionsTransitionGuardMultiple.new(:log => show_debug_log, :fail_transition_guard => true) callback.aasm(:left).current_state unless show_debug_log expect(callback).to receive(:before).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered expect(callback).to receive(:exit_open).once.ordered expect(callback).to receive(:aasm_write_state).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:after_exit_open).once.ordered expect(callback).to receive(:after).once.ordered expect(callback).to_not receive(:transitioning) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:after_enter_closed) end callback.close! expect(callback.aasm(:left).current_state).to eql :failed end it "does not run any state callback if guard is defined with block" do callback = Callbacks::GuardWithinBlockMultiple.new #(:log => true, :fail_transition_guard => true) callback.aasm(:left).current_state expect(callback).to receive(:before).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:transitioning) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after) expect { callback.close! }.to raise_error(AASM::InvalidTransition) end end it "should properly pass arguments" do cb = Callbacks::WithArgsMultiple.new(:log => false) cb.aasm(:left).current_state cb.reset_data cb.close!(:arg1, :arg2) expect(cb.data).to eql 'before(:arg1,:arg2) before_exit_open(:arg1,:arg2) transition_proc(:arg1,:arg2) before_enter_closed(:arg1,:arg2) aasm_write_state after_exit_open(:arg1,:arg2) after_enter_closed(:arg1,:arg2) after(:arg1,:arg2)' end it "should call the callbacks given the to-state as argument" do cb = Callbacks::WithStateArgMultiple.new expect(cb).to receive(:before_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:transition_method2).with(:arg1).once.ordered expect(cb).to receive(:before_success_method).with(:arg1).once.ordered expect(cb).to receive(:success_method).with(:arg1).once.ordered expect(cb).to receive(:after_method).with(:arg1).once.ordered cb.close!(:out_to_lunch, :arg1) cb = Callbacks::WithStateArgMultiple.new some_object = double('some object') expect(cb).to receive(:before_method).with(some_object).once.ordered expect(cb).to receive(:transition_method2).with(some_object).once.ordered expect(cb).to receive(:before_success_method).with(some_object).once.ordered expect(cb).to receive(:success_method).with(some_object).once.ordered expect(cb).to receive(:after_method).with(some_object).once.ordered cb.close!(:out_to_lunch, some_object) end it "should call the proper methods just with arguments" do cb = Callbacks::WithStateArgMultiple.new expect(cb).to receive(:before_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:after_method).with(:arg1).once.ordered cb.close!(:arg1) cb = Callbacks::WithStateArgMultiple.new some_object = double('some object') expect(cb).to receive(:before_method).with(some_object).once.ordered expect(cb).to receive(:transition_method).with(some_object).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:after_method).with(some_object).once.ordered cb.close!(some_object) end end # callbacks for the new DSL describe 'event callbacks' do describe "with an error callback defined" do before do class FooCallbackMultiple # this hack is needed to allow testing of parameters, since RSpec # destroys a method's arity when mocked attr_accessor :data aasm(:left) do event :safe_close, :success => :success_callback, :error => :error_callback do transitions :to => :closed, :from => [:open] end end end @foo = FooCallbackMultiple.new end context "error_callback defined" do it "should run error_callback if an exception is raised" do def @foo.error_callback(e) @data = [e] end allow(@foo).to receive(:before_enter).and_raise(e = StandardError.new) @foo.safe_close! expect(@foo.data).to eql [e] end it "should run error_callback without parameters if callback does not support any" do def @foo.error_callback(e) @data = [] end allow(@foo).to receive(:before_enter).and_raise(e = StandardError.new) @foo.safe_close!('arg1', 'arg2') expect(@foo.data).to eql [] end it "should run error_callback with parameters if callback supports them" do def @foo.error_callback(e, arg1, arg2) @data = [arg1, arg2] end allow(@foo).to receive(:before_enter).and_raise(e = StandardError.new) @foo.safe_close!('arg1', 'arg2') expect(@foo.data).to eql ['arg1', 'arg2'] end end it "should raise NoMethodError if exception is raised and error_callback is declared but not defined" do allow(@foo).to receive(:before_enter).and_raise(StandardError) expect{@foo.safe_close!}.to raise_error(NoMethodError) end it "should propagate an error if no error callback is declared" do allow(@foo).to receive(:before_enter).and_raise("Cannot enter safe") expect{@foo.close!}.to raise_error(StandardError, "Cannot enter safe") end end describe "with aasm_event_fired defined" do before do @foo = FooMultiple.new def @foo.aasm_event_fired(event, from, to); end end it 'should call it for successful bang fire' do expect(@foo).to receive(:aasm_event_fired).with(:close, :open, :closed) @foo.close! end it 'should call it for successful non-bang fire' do expect(@foo).to receive(:aasm_event_fired) @foo.close end it 'should not call it for failing bang fire' do allow(@foo.aasm(:left)).to receive(:set_current_state_with_persistence).and_return(false) expect(@foo).not_to receive(:aasm_event_fired) @foo.close! end end describe "with aasm_event_failed defined" do before do @foo = FooMultiple.new def @foo.aasm_event_failed(event, from); end end it 'should call it when transition failed for bang fire' do expect(@foo).to receive(:aasm_event_failed).with(:null, :open) expect{ @foo.null! }.to raise_error(AASM::InvalidTransition, "Event 'null' cannot transition from 'open'. Failed callback(s): [:always_false].") end it 'should call it when transition failed for non-bang fire' do expect(@foo).to receive(:aasm_event_failed).with(:null, :open) expect{ @foo.null }.to raise_error(AASM::InvalidTransition, "Event 'null' cannot transition from 'open'. Failed callback(s): [:always_false].") end it 'should not call it if persist fails for bang fire' do allow(@foo.aasm(:left)).to receive(:set_current_state_with_persistence).and_return(false) expect(@foo).to receive(:aasm_event_failed) @foo.close! end end end # event callbacks
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/exception_spec.rb
spec/unit/exception_spec.rb
require 'spec_helper' describe AASM::InvalidTransition do it 'should not be lazy detecting originating state' do process = ProcessWithNewDsl.new expect { process.stop! }.to raise_error do |err| process.start expect(err.message).to eql("Event 'stop' cannot transition from 'sleeping'.") end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/callbacks_spec.rb
spec/unit/callbacks_spec.rb
require 'spec_helper' Dir[File.dirname(__FILE__) + "/../models/callbacks/*.rb"].sort.each { |f| require File.expand_path(f) } shared_examples 'an implemented callback that accepts error' do context 'with callback defined' do it "should run error_callback if an exception is raised and always return false" do aasm_model.class.send(:define_method, callback_name) do |e| @data = [e] end allow(aasm_model).to receive(:before_enter).and_raise(e = StandardError.new) expect(aasm_model.safe_close!).to be false expect(aasm_model.data).to eql [e] end it "should run error_callback without parameters if callback does not support any" do aasm_model.class.send(:define_method, callback_name) do |e| @data = [] end allow(aasm_model).to receive(:before_enter).and_raise(e = StandardError.new) aasm_model.safe_close!('arg1', 'arg2') expect(aasm_model.data).to eql [] end it "should run error_callback with parameters if callback supports them" do aasm_model.class.send(:define_method, callback_name) do |e, arg1, arg2| @data = [arg1, arg2] end allow(aasm_model).to receive(:before_enter).and_raise(e = StandardError.new) aasm_model.safe_close!('arg1', 'arg2') expect(aasm_model.data).to eql ['arg1', 'arg2'] end end end shared_examples 'an implemented callback' do context 'with callback defined' do it 'should run callback without parameters if callback does not support any' do aasm_model.class.send(:define_method, callback_name) do @data = ['callback-was-called'] end aasm_model.safe_close! expect(aasm_model.data).to eql ['callback-was-called'] end it 'should run callback with parameters if callback supports them' do aasm_model.class.send(:define_method, callback_name) do |arg1, arg2| @data = [arg1, arg2] end aasm_model.safe_close!('arg1', 'arg2') expect(aasm_model.data).to eql ['arg1', 'arg2'] end end end describe 'callbacks for the new DSL' do it "be called in order" do show_debug_log = false callback = Callbacks::Basic.new(:log => show_debug_log) callback.aasm.current_state unless show_debug_log expect(callback).to receive(:before_all_events).once.ordered expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered # these should be before the state changes expect(callback).to receive(:exit_open).once.ordered # expect(callback).to receive(:event_guard).once.ordered.and_return(true) # expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:after_all_transitions).once.ordered expect(callback).to receive(:after_transition).once.ordered expect(callback).to receive(:before_enter_closed).once.ordered expect(callback).to receive(:enter_closed).once.ordered expect(callback).to receive(:aasm_write_state).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:after_exit_open).once.ordered # these should be after the state changes expect(callback).to receive(:after_enter_closed).once.ordered expect(callback).to receive(:after_event).once.ordered expect(callback).to receive(:after_all_events).once.ordered expect(callback).to receive(:ensure_event).once.ordered expect(callback).to receive(:ensure_on_all_events).once.ordered end callback.close! end it "works fine after reload" do show_debug_log = false callback = Callbacks::Basic.new(:log => show_debug_log) callback.aasm.current_state # reload the class Callbacks.send(:remove_const, :Basic) load 'models/callbacks/basic.rb' unless show_debug_log expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered # these should be before the state changes expect(callback).to receive(:exit_open).once.ordered # expect(callback).to receive(:event_guard).once.ordered.and_return(true) # expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:after_all_transitions).once.ordered expect(callback).to receive(:after_transition).once.ordered expect(callback).to receive(:before_enter_closed).once.ordered expect(callback).to receive(:enter_closed).once.ordered expect(callback).to receive(:aasm_write_state).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:event_before_success).once.ordered expect(callback).to receive(:success_transition).once.ordered.and_return(true) # these should be after the state changes expect(callback).to receive(:after_exit_open).once.ordered expect(callback).to receive(:after_enter_closed).once.ordered expect(callback).to receive(:after_event).once.ordered end callback.close! end it 'does not run callbacks if firing an unknown event' do show_debug_log = false callback = Callbacks::Basic.new(:log => show_debug_log) expect(callback).to_not receive(:before_all_events).ordered expect(callback).to_not receive(:before_event).ordered expect(callback).to_not receive(:event_guard).ordered expect(callback).to_not receive(:transition_guard) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:after_all_transitions) expect(callback).to_not receive(:after_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:event_before_success) expect(callback).to_not receive(:success_transition) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after_event) expect(callback).to_not receive(:after_all_events) expect(callback).to_not receive(:ensure_event).ordered expect(callback).to_not receive(:ensure_on_all_events).ordered expect { callback.aasm.fire(:unknown) }.to raise_error(AASM::UndefinedEvent, "Event :unknown doesn't exist") expect { callback.aasm.fire!(:unknown) }.to raise_error(AASM::UndefinedEvent, "Event :unknown! doesn't exist") end it "does not run any state callback if the event guard fails" do callback = Callbacks::Basic.new(:log => false) callback.aasm.current_state expect(callback).to receive(:before_all_events).once.ordered expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(false) expect(callback).to_not receive(:transition_guard) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:after_all_transitions) expect(callback).to_not receive(:after_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:event_before_success) expect(callback).to_not receive(:success_transition) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after_event) expect(callback).to_not receive(:after_all_events) expect(callback).to receive(:ensure_event).once.ordered expect(callback).to receive(:ensure_on_all_events).once.ordered expect { callback.close! }.to raise_error(AASM::InvalidTransition) end it "handles private callback methods as well" do show_debug_log = false callback = Callbacks::PrivateMethod.new(:log => show_debug_log) callback.aasm.current_state expect { callback.close! }.to_not raise_error end context "if the transition guard fails" do it "does not run any state callback if guard is defined inline" do show_debug_log = false callback = Callbacks::Basic.new(:log => show_debug_log, :fail_transition_guard => true) callback.aasm.current_state unless show_debug_log expect(callback).to receive(:before_all_events).once.ordered expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:after_all_transitions) expect(callback).to_not receive(:after_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:event_before_success) expect(callback).to_not receive(:success_transition) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after_event) expect(callback).to_not receive(:after_all_events) expect(callback).to receive(:ensure_event).once.ordered expect(callback).to receive(:ensure_on_all_events).once.ordered end expect { callback.close! }.to raise_error(AASM::InvalidTransition) end it "does not propagate failures to next attempt of same transition" do callback = Callbacks::Basic.new(:log => false, :fail_transition_guard => true) expect { callback.close! }.to raise_error(AASM::InvalidTransition, "Event 'close' cannot transition from 'open'. Failed callback(s): [:transition_guard].") expect { callback.close! }.to raise_error(AASM::InvalidTransition, "Event 'close' cannot transition from 'open'. Failed callback(s): [:transition_guard].") end it "does not propagate failures to next attempt of same event when no transition is applicable" do callback = Callbacks::Basic.new(:log => false, :fail_transition_guard => true) expect { callback.close! }.to raise_error(AASM::InvalidTransition, "Event 'close' cannot transition from 'open'. Failed callback(s): [:transition_guard].") callback.aasm.current_state = :closed expect { callback.close! }.to raise_error(AASM::InvalidTransition, "Event 'close' cannot transition from 'closed'.") end it "does not run transition_guard twice for multiple permitted transitions" do show_debug_log = false callback = Callbacks::MultipleTransitionsTransitionGuard.new(:log => show_debug_log, :fail_transition_guard => true) callback.aasm.current_state unless show_debug_log expect(callback).to receive(:before).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered expect(callback).to receive(:exit_open).once.ordered expect(callback).to receive(:aasm_write_state).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:after_exit_open).once.ordered expect(callback).to receive(:after).once.ordered expect(callback).to_not receive(:transitioning) expect(callback).to_not receive(:event_before_success) expect(callback).to_not receive(:success_transition) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:after_enter_closed) end callback.close! expect(callback.aasm.current_state).to eql :failed end it "does not run any state callback if guard is defined with block" do callback = Callbacks::GuardWithinBlock.new #(:log => true, :fail_transition_guard => true) callback.aasm.current_state expect(callback).to receive(:before).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(false) expect(callback).to_not receive(:before_exit_open) expect(callback).to_not receive(:exit_open) expect(callback).to_not receive(:transitioning) expect(callback).to_not receive(:before_enter_closed) expect(callback).to_not receive(:enter_closed) expect(callback).to_not receive(:aasm_write_state) expect(callback).to_not receive(:event_before_success) expect(callback).to_not receive(:success_transition) expect(callback).to_not receive(:after_exit_open) expect(callback).to_not receive(:after_enter_closed) expect(callback).to_not receive(:after) expect { callback.close! }.to raise_error(AASM::InvalidTransition) end end it "should properly pass arguments" do cb = Callbacks::WithArgs.new(:log => false) cb.aasm.current_state cb.reset_data cb.close!(:arg1, :arg2) expect(cb.data).to eql 'before(:arg1,:arg2) before_exit_open(:arg1,:arg2) transition_proc(:arg1,:arg2) before_enter_closed(:arg1,:arg2) aasm_write_state transition_success(:arg1,:arg2) after_exit_open(:arg1,:arg2) after_enter_closed(:arg1,:arg2) after(:arg1,:arg2)' end it "should call the callbacks given the to-state as argument" do cb = Callbacks::WithStateArg.new expect(cb).to receive(:before_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:success_method).never expect(cb).to receive(:transition_method2).with(:arg1).once.ordered expect(cb).to receive(:success_method2).with(:arg1).once.ordered expect(cb).to receive(:after_method).with(:arg1).once.ordered cb.close!(:out_to_lunch, :arg1) cb = Callbacks::WithStateArg.new some_object = double('some object') expect(cb).to receive(:before_method).with(some_object).once.ordered expect(cb).to receive(:transition_method2).with(some_object).once.ordered expect(cb).to receive(:success_method2).with(some_object).once.ordered expect(cb).to receive(:after_method).with(some_object).once.ordered cb.close!(:out_to_lunch, some_object) end it "should call the proper methods just with arguments" do cb = Callbacks::WithStateArg.new expect(cb).to receive(:before_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).with(:arg1).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:before_success_method).with(:arg1).once.ordered expect(cb).to receive(:success_method).with(:arg1).once.ordered expect(cb).to receive(:success_method3).with(:arg1).once.ordered expect(cb).to receive(:success_method).never expect(cb).to receive(:after_method).with(:arg1).once.ordered cb.close!(:arg1) cb = Callbacks::WithStateArg.new some_object = double('some object') expect(cb).to receive(:before_method).with(some_object).once.ordered expect(cb).to receive(:transition_method).with(some_object).once.ordered expect(cb).to receive(:transition_method).never expect(cb).to receive(:before_success_method).with(some_object).once.ordered expect(cb).to receive(:success_method).with(some_object).once.ordered expect(cb).to receive(:success_method3).with(some_object).once.ordered expect(cb).to receive(:success_method).never expect(cb).to receive(:after_method).with(some_object).once.ordered cb.close!(some_object) end end describe 'event callbacks' do describe "with an error callback defined" do before do class Foo # this hack is needed to allow testing of parameters, since RSpec # destroys a method's arity when mocked attr_accessor :data aasm do event :safe_close, :success => :success_callback, :error => :error_callback do transitions :to => :closed, :from => [:open], :success => :transition_success_callback end end end @foo = Foo.new end it_behaves_like 'an implemented callback that accepts error' do let(:aasm_model) { @foo } let(:callback_name) { :error_callback } end it "should raise NoMethodError if exception is raised and error_callback is declared but not defined" do allow(@foo).to receive(:before_enter).and_raise(StandardError) expect{@foo.safe_close!}.to raise_error(NoMethodError) end it "should propagate an error if no error callback is declared" do allow(@foo).to receive(:before_enter).and_raise("Cannot enter safe") expect{@foo.close!}.to raise_error(StandardError, "Cannot enter safe") end end describe 'with an ensure callback defined' do before do class Foo # this hack is needed to allow testing of parameters, since RSpec # destroys a method's arity when mocked attr_accessor :data aasm do event :safe_close, :success => :success_callback, :ensure => :ensure_callback do transitions :to => :closed, :from => [:open] end end end @foo = Foo.new end it_behaves_like 'an implemented callback' do let(:aasm_model) { @foo } let(:callback_name) { :ensure_callback } end it "should raise NoMethodError if ensure_callback is declared but not defined" do expect{@foo.safe_close!}.to raise_error(NoMethodError) end it "should not raise any error if no ensure_callback is declared" do expect{@foo.close!}.to_not raise_error end end describe "with aasm_event_fired defined" do before do @foo = Foo.new def @foo.aasm_event_fired(event, from, to); end end it 'should call it for successful bang fire' do expect(@foo).to receive(:aasm_event_fired).with(:close, :open, :closed) @foo.close! end it 'should call it for successful non-bang fire' do expect(@foo).to receive(:aasm_event_fired) @foo.close end it 'should not call it for failing bang fire' do allow(@foo.aasm).to receive(:set_current_state_with_persistence).and_return(false) expect(@foo).not_to receive(:aasm_event_fired) @foo.close! end end describe "with aasm_event_failed defined" do before do @foo = Foo.new def @foo.aasm_event_failed(event, from); end end it 'should call it when transition failed for bang fire' do expect(@foo).to receive(:aasm_event_failed).with(:null, :open) expect {@foo.null!}.to raise_error(AASM::InvalidTransition) end it 'should call it when transition failed for non-bang fire' do expect(@foo).to receive(:aasm_event_failed).with(:null, :open) expect {@foo.null}.to raise_error(AASM::InvalidTransition) end it 'should not call it if persist fails for bang fire' do allow(@foo.aasm).to receive(:set_current_state_with_persistence).and_return(false) expect(@foo).to receive(:aasm_event_failed) @foo.close! end end end describe 'global error_on_all_events_callback callbacks' do describe "with an error_on_all_events" do before do class FooGlobal # this hack is needed to allow testing of parameters, since RSpec # destroys a method's arity when mocked attr_accessor :data aasm do error_on_all_events :error_on_all_events_callback event :safe_close do transitions :to => :closed, :from => [:open] end end end @foo = FooGlobal.new end it_behaves_like 'an implemented callback that accepts error' do let(:aasm_model) { @foo } let(:callback_name) { :error_on_all_events_callback } end it "should raise NoMethodError if exception is raised and error_callback is declared but not defined" do allow(@foo).to receive(:before_enter).and_raise(StandardError) expect{@foo.safe_close!}.to raise_error(NoMethodError) end it "should raise NoMethodError if no error callback is declared" do allow(@foo).to receive(:before_enter).and_raise("Cannot enter safe") expect{@foo.close!}.to raise_error(NoMethodError) end end end describe 'global ensure_on_all_events_callback callbacks' do describe "with an ensure_on_all_events" do before do class FooGlobal # this hack is needed to allow testing of parameters, since RSpec # destroys a method's arity when mocked attr_accessor :data aasm do ensure_on_all_events :ensure_on_all_events_callback event :safe_close do transitions :to => :closed, :from => [:open] end end end @foo = FooGlobal.new end it_behaves_like 'an implemented callback' do let(:aasm_model) { @foo } let(:callback_name) { :ensure_on_all_events_callback } end it "should raise NoMethodError if ensure_on_all_events callback is declared but not defined" do expect{@foo.safe_close!}.to raise_error(NoMethodError) end it "should raise NoMethodError if no ensure_on_all_events callback is declared" do expect{@foo.close!}.to raise_error(NoMethodError) end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_with_params_multiple_spec.rb
spec/unit/guard_with_params_multiple_spec.rb
require 'spec_helper' describe "guards with params" do let(:guard) { GuardWithParamsMultiple.new } let(:user) {GuardParamsClass.new} it "list permitted states" do expect(guard.aasm(:left).states({:permitted => true}, user).map(&:name)).to eql [:reviewed] end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/multiple_transitions_that_differ_only_by_guard_spec.rb
spec/unit/multiple_transitions_that_differ_only_by_guard_spec.rb
require 'spec_helper' describe "multiple transitions that differ only by guard" do let(:job) { MultipleTransitionsThatDifferOnlyByGuard.new } it 'does not follow the first transition if its guard fails' do expect{job.go}.not_to raise_error end it 'executes the second transition\'s callbacks' do job.go expect(job.executed_second).to be_truthy end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/subclassing_spec.rb
spec/unit/subclassing_spec.rb
require 'spec_helper' describe 'subclassing' do it 'should have the parent states' do SuperClass.aasm.states.each do |state| expect(SubClassWithMoreStates.aasm.states).to include(state) end expect(SubClass.aasm.states).to eq(SuperClass.aasm.states) end it 'should not add the child states to the parent machine' do expect(SuperClass.aasm.states).not_to include(:foo) end it 'should have the same events as its parent' do expect(SubClass.aasm.events).to eq(SuperClass.aasm.events) end it 'should know how to respond to question methods' do expect(SubClass.new.may_foo?).to be_truthy end it 'should not break if I call methods from super class' do son = SubClass.new son.update_state expect(son.aasm.current_state).to eq(:ended) end it 'should allow the child to modify its state machine' do son = SubClass.new expect(son.called_after).to eq(nil) son.foo expect(son.called_after).to eq(true) global_callbacks = SubClass.aasm.state_machine.global_callbacks expect(global_callbacks).to_not be_empty expect(global_callbacks[:after_all_transitions]).to eq :after_all_event end it 'should not modify the parent state machine' do super_class_event = SuperClass.aasm.events.select { |event| event.name == :foo }.first expect(super_class_event.options).to be_empty expect(SuperClass.aasm.state_machine.global_callbacks).to be_empty end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/api_spec.rb
spec/unit/api_spec.rb
require 'spec_helper' if defined?(ActiveRecord) require 'models/default_state.rb' require 'models/provided_state.rb' require 'models/active_record/persisted_state.rb' require 'models/active_record/provided_and_persisted_state.rb' load_schema describe "reading the current state" do it "uses the AASM default" do expect(DefaultState.new.aasm.current_state).to eql :alpha end it "uses display option" do expect(DefaultState.new.aasm.human_state).to eql "ALPHA" end it "uses the provided method" do expect(ProvidedState.new.aasm.current_state).to eql :beta end it "uses the persistence storage" do expect(PersistedState.new.aasm.current_state).to eql :alpha end it "uses the provided method even if persisted" do expect(ProvidedAndPersistedState.new.aasm.current_state).to eql :gamma end context "after dup" do it "uses the persistence storage" do source = PersistedState.create! copy = source.dup copy.save! copy.release! expect(source.aasm_state).to eql 'alpha' expect(source.aasm.current_state).to eql :alpha source2 = PersistedState.find(source.id) expect(source2.reload.aasm_state).to eql 'alpha' expect(source2.aasm.current_state).to eql :alpha expect(copy.aasm_state).to eql 'beta' expect(copy.aasm.current_state).to eql :beta end end end describe "writing and persisting the current state" do it "uses the AASM default" do o = DefaultState.new o.release! expect(o.persisted_store).to be_nil end it "uses the provided method" do o = ProvidedState.new o.release! expect(o.persisted_store).to eql :beta end it "uses the persistence storage" do o = PersistedState.new o.release! expect(o.persisted_store).to be_nil end it "uses the provided method even if persisted" do o = ProvidedAndPersistedState.new o.release! expect(o.persisted_store).to eql :beta end end describe "writing the current state without persisting it" do it "uses the AASM default" do o = DefaultState.new o.release expect(o.transient_store).to be_nil end it "uses the provided method" do o = ProvidedState.new o.release expect(o.transient_store).to eql :beta end it "uses the persistence storage" do o = PersistedState.new o.release expect(o.transient_store).to be_nil end it "uses the provided method even if persisted" do o = ProvidedAndPersistedState.new o.release expect(o.transient_store).to eql :beta end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/edge_cases_spec.rb
spec/unit/edge_cases_spec.rb
require 'spec_helper' describe "edge cases" do describe "for classes with multiple state machines" do it "allows accessing a multiple state machine class without state machine name" do # it's like starting to define a new state machine within the # requested class expect(SimpleMultipleExample.aasm.states.map(&:name)).to be_empty end it "do not know yet" do example = ComplexExampleMultiple.new expect { example.aasm.states.inspect }.to raise_error(AASM::UnknownStateMachineError) end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/initial_state_spec.rb
spec/unit/initial_state_spec.rb
require 'spec_helper' describe 'initial states' do it 'should use the first state defined if no initial state is given' do expect(NoInitialState.new.aasm.current_state).to eq(:read) end it 'should determine initial state from the Proc results' do expect(InitialStateProc.new(InitialStateProc::RICH - 1).aasm.current_state).to eq(:selling_bad_mortgages) expect(InitialStateProc.new(InitialStateProc::RICH + 1).aasm.current_state).to eq(:retired) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/namespaced_multiple_example_spec.rb
spec/unit/namespaced_multiple_example_spec.rb
require 'spec_helper' describe 'state machine' do let(:namespaced) { NamespacedMultipleExample.new } it 'starts with an initial state' do expect(namespaced.aasm(:status).current_state).to eq(:unapproved) expect(namespaced).to respond_to(:unapproved?) expect(namespaced).to be_unapproved expect(namespaced.aasm(:review_status).current_state).to eq(:unapproved) expect(namespaced).to respond_to(:review_unapproved?) expect(namespaced).to be_review_unapproved expect(namespaced.aasm(:car).current_state).to eq(:unsold) expect(namespaced).to respond_to(:car_unsold?) expect(namespaced).to be_car_unsold end it 'allows transitions to other states' do expect(namespaced).to respond_to(:approve) expect(namespaced).to respond_to(:approve!) namespaced.approve! expect(namespaced).to respond_to(:approved?) expect(namespaced).to be_approved expect(namespaced).to respond_to(:approve_review) expect(namespaced).to respond_to(:approve_review!) namespaced.approve_review! expect(namespaced).to respond_to(:review_approved?) expect(namespaced).to be_review_approved expect(namespaced).to respond_to(:sell_car) expect(namespaced).to respond_to(:sell_car!) namespaced.sell_car! expect(namespaced).to respond_to(:car_sold?) expect(namespaced).to be_car_sold end it 'denies transitions to other states' do expect {namespaced.unapprove}.to raise_error(AASM::InvalidTransition) expect {namespaced.unapprove!}.to raise_error(AASM::InvalidTransition) namespaced.approve expect {namespaced.approve}.to raise_error(AASM::InvalidTransition) expect {namespaced.approve!}.to raise_error(AASM::InvalidTransition) namespaced.unapprove expect {namespaced.unapprove_review}.to raise_error(AASM::InvalidTransition) expect {namespaced.unapprove_review!}.to raise_error(AASM::InvalidTransition) namespaced.approve_review expect {namespaced.approve_review}.to raise_error(AASM::InvalidTransition) expect {namespaced.approve_review!}.to raise_error(AASM::InvalidTransition) namespaced.unapprove_review expect {namespaced.return_car}.to raise_error(AASM::InvalidTransition) expect {namespaced.return_car!}.to raise_error(AASM::InvalidTransition) namespaced.sell_car expect {namespaced.sell_car}.to raise_error(AASM::InvalidTransition) expect {namespaced.sell_car!}.to raise_error(AASM::InvalidTransition) namespaced.return_car end it 'defines constants for each state name' do expect(NamespacedMultipleExample::STATE_UNAPPROVED).to eq(:unapproved) expect(NamespacedMultipleExample::STATE_APPROVED).to eq(:approved) expect(NamespacedMultipleExample::STATE_REVIEW_UNAPPROVED).to eq(:unapproved) expect(NamespacedMultipleExample::STATE_REVIEW_APPROVED).to eq(:approved) expect(NamespacedMultipleExample::STATE_CAR_UNSOLD).to eq(:unsold) expect(NamespacedMultipleExample::STATE_CAR_SOLD).to eq(:sold) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_with_params_spec.rb
spec/unit/guard_with_params_spec.rb
require 'spec_helper' describe "guards with params" do let(:guard) { GuardWithParams.new } let(:user) {GuardParamsClass.new} it "list permitted states" do expect(guard.aasm.states({:permitted => true}, user).map(&:name)).to eql [:reviewed] end it "list no states if user is blank" do expect(guard.aasm.states({:permitted => true}, nil).map(&:name)).to eql [] end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/initial_state_multiple_spec.rb
spec/unit/initial_state_multiple_spec.rb
require 'spec_helper' describe 'initial states' do it 'should use the first state defined if no initial state is given' do expect(NoInitialStateMultiple.new.aasm(:left).current_state).to eq(:read) end it 'should determine initial state from the Proc results' do balance = InitialStateProcMultiple::RICH - 1 expect(InitialStateProcMultiple.new(balance).aasm(:left).current_state).to eq(:selling_bad_mortgages) balance = InitialStateProcMultiple::RICH + 1 expect(InitialStateProcMultiple.new(balance).aasm(:left).current_state).to eq(:retired) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/class_with_keyword_arguments_spec.rb
spec/unit/class_with_keyword_arguments_spec.rb
require 'spec_helper' describe ClassWithKeywordArguments do let(:state_machine) { ClassWithKeywordArguments.new } let(:resource) { double('resource', value: 1) } context 'when using optional keyword arguments' do it 'changes state successfully to closed_temporarily' do expect(state_machine.close_temporarily!(my_optional_arg: 'closed_temporarily')).to be_truthy expect(state_machine.my_attribute).to eq('closed_temporarily') end it 'changes state successfully to closed_temporarily when optional keyword argument is not provided' do expect(state_machine.close_temporarily!()).to be_truthy expect(state_machine.my_attribute).to eq('closed_forever') end end it 'changes state successfully to closed_forever' do expect(state_machine.close_forever!).to be_truthy expect(state_machine.my_attribute).to eq('closed_forever') end it 'changes state successfully to closed_then_something_else' do expect(state_machine.close_then_something_else!(my_required_arg: 'closed_then_something_else')).to be_truthy expect(state_machine.my_attribute).to eq('closed_then_something_else') end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/complex_example_spec.rb
spec/unit/complex_example_spec.rb
require 'spec_helper' describe 'on initialization' do let(:auth) {ComplexExample.new} it 'should be in the pending state' do expect(auth.aasm.current_state).to eq(:pending) end it 'should have an activation code' do expect(auth.has_activation_code?).to be_truthy expect(auth.activation_code).not_to be_nil end end describe 'when being unsuspended' do let(:auth) {ComplexExample.new} it 'should be able to be unsuspended' do auth.activate! auth.suspend! expect(auth.may_unsuspend?).to be true end it 'should not be able to be unsuspended into active' do auth.suspend! expect(auth.may_unsuspend?(:active)).not_to be true end it 'should be able to be unsuspended into active if polite' do auth.suspend! expect(auth.may_wait?(:waiting, :please)).to be true auth.wait!(:please) end it 'should not be able to be unsuspended into active if not polite' do auth.suspend! expect(auth.may_wait?(:waiting)).not_to be true expect(auth.may_wait?(:waiting, :rude)).not_to be true expect {auth.wait!(:rude)}.to raise_error(AASM::InvalidTransition) expect {auth.wait!}.to raise_error(AASM::InvalidTransition) end it 'should not be able to be unpassified' do auth.activate! auth.suspend! auth.unsuspend! expect(auth.may_unpassify?).not_to be true expect {auth.unpassify!}.to raise_error(AASM::InvalidTransition) end it 'should be active if previously activated' do auth.activate! auth.suspend! auth.unsuspend! expect(auth.aasm.current_state).to eq(:active) end it 'should be pending if not previously activated, but an activation code is present' do auth.suspend! auth.unsuspend! expect(auth.aasm.current_state).to eq(:pending) end it 'should be passive if not previously activated and there is no activation code' do auth.activation_code = nil auth.suspend! auth.unsuspend! expect(auth.aasm.current_state).to eq(:passive) end it "should be able to fire known events" do expect(auth.aasm.may_fire_event?(:activate)).to be true end it "should be able to fire event by name" do expect(auth.aasm.fire(:activate)).to be true expect(auth.aasm.current_state).to eq(:active) end it "should be able to fire! event by name" do expect(auth.aasm.fire!(:activate)).to be true expect(auth.aasm.current_state).to eq(:active) end it "should not be able to fire unknown events" do expect(auth.aasm.may_fire_event?(:unknown)).to be false end it "should raise AASM::UndefinedState when firing unknown events" do expect { auth.aasm.fire(:unknown) }.to raise_error(AASM::UndefinedEvent, "Event :unknown doesn't exist") end it "should raise AASM::UndefinedState when firing unknown bang events" do expect { auth.aasm.fire!(:unknown) }.to raise_error(AASM::UndefinedEvent, "Event :unknown! doesn't exist") end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/invoker_spec.rb
spec/unit/invoker_spec.rb
require 'spec_helper' describe AASM::Core::Invoker do let(:target) { nil } let(:record) { double } let(:args) { [] } subject { described_class.new(target, record, args) } describe '#with_options' do context 'when passing array as a subject' do context 'and "guard" option is set to true' do let(:target) { [subject_1, subject_2] } before { subject.with_options(guard: true) } context 'and all the subjects are truthy' do let(:subject_1) { Proc.new { true } } let(:subject_2) { Proc.new { true } } it 'then returns "true" while invoking' do expect(subject.invoke).to eq(true) end end context 'and any subject is falsely' do let(:subject_1) { Proc.new { false } } let(:subject_2) { Proc.new { true } } it 'then returns "false" while invoking' do expect(subject.invoke).to eq(false) end end end context 'and "unless" option is set to true' do let(:target) { [subject_1, subject_2] } before { subject.with_options(unless: true) } context 'and all the subjects are falsely' do let(:subject_1) { Proc.new { false } } let(:subject_2) { Proc.new { false } } it 'then returns "true" while invoking' do expect(subject.invoke).to eq(true) end end context 'and any subject is truthy' do let(:subject_1) { Proc.new { false } } let(:subject_2) { Proc.new { true } } it 'then returns "false" while invoking' do expect(subject.invoke).to eq(false) end end end end end describe '#with_failures' do let(:concrete_invoker) { AASM::Core::Invokers::ProcInvoker } let(:target) { Proc.new {} } it 'then sets failures buffer for concrete invokers' do expect_any_instance_of(concrete_invoker) .to receive(:with_failures) .and_call_original subject.invoke end end describe '#with_default_return_value' do context 'when return value is "true"' do before { subject.with_default_return_value(true) } it 'then returns "true" when was not picked up by any invoker' do expect(subject.invoke).to eq(true) end end context 'when return value is "false"' do before { subject.with_default_return_value(false) } it 'then returns "false" when was not picked up by any invoker' do expect(subject.invoke).to eq(false) end end end describe '#invoke' do context 'when subject is a proc' do let(:concrete_invoker) { AASM::Core::Invokers::ProcInvoker } let(:target) { Proc.new {} } it 'then calls proc invoker' do expect_any_instance_of(concrete_invoker) .to receive(:invoke) .and_call_original expect(record).to receive(:instance_exec) subject.invoke end end context 'when subject is a class' do let(:concrete_invoker) { AASM::Core::Invokers::ClassInvoker } let(:target) { Class.new { def call; end } } it 'then calls proc invoker' do expect_any_instance_of(concrete_invoker) .to receive(:invoke) .and_call_original expect_any_instance_of(target).to receive(:call) subject.invoke end end context 'when subject is a literal' do let(:concrete_invoker) { AASM::Core::Invokers::LiteralInvoker } let(:record) { double(invoke_me: nil) } let(:target) { :invoke_me } it 'then calls literal invoker' do expect_any_instance_of(concrete_invoker) .to receive(:invoke) .and_call_original expect(record).to receive(:invoke_me) subject.invoke end end context 'when subject is an array of procs' do let(:subject_1) { Proc.new {} } let(:subject_2) { Proc.new {} } let(:target) { [subject_1, subject_2] } it 'then calls each proc' do expect(record).to receive(:instance_exec).twice subject.invoke end end context 'when subject is an array of classes' do let(:subject_1) { Class.new { def call; end } } let(:subject_2) { Class.new { def call; end } } let(:target) { [subject_1, subject_2] } it 'then calls each class' do expect_any_instance_of(subject_1).to receive(:call) expect_any_instance_of(subject_2).to receive(:call) subject.invoke end end context 'when subject is an array of literals' do let(:subject_1) { :method_one } let(:subject_2) { :method_two } let(:record) { double(method_one: nil, method_two: nil) } let(:target) { [subject_1, subject_2] } it 'then calls each class' do expect(record).to receive(:method_one) expect(record).to receive(:method_two) subject.invoke end end context 'when subject is not supported' do let(:target) { nil } it 'then just returns default value' do expect(subject.invoke).to eq(described_class::DEFAULT_RETURN_VALUE) end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/simple_custom_example_spec.rb
spec/unit/simple_custom_example_spec.rb
require 'spec_helper' describe 'Custom AASM::Base' do context 'when aasm_with invoked with SimpleCustomExample' do let(:simple_custom) { SimpleCustomExample.new } subject do simple_custom.fill_out! simple_custom.authorise end it 'has invoked authorizable?' do expect { subject }.to change { simple_custom.authorizable_called }.from(nil).to(true) end it 'has invoked fillable?' do expect { subject }.to change { simple_custom.fillable_called }.from(nil).to(true) end it 'has two transition counts' do expect { subject }.to change { simple_custom.transition_count }.from(nil).to(2) end end context 'when aasm_with invoked with non AASM::Base' do subject do Class.new do include AASM aasm :with_klass => String do end end end it 'should raise an ArgumentError' do expect { subject }.to raise_error(ArgumentError, 'The class String must inherit from AASM::Base!') end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/rspec_matcher_spec.rb
spec/unit/rspec_matcher_spec.rb
require 'spec_helper' describe 'state machine' do let(:simple) { SimpleExample.new } let(:multiple) { SimpleMultipleExample.new } describe 'transition_from' do it "works for simple state machines" do expect(simple).to transition_from(:initialised).to(:filled_out).on_event(:fill_out) expect(simple).to_not transition_from(:initialised).to(:authorised).on_event(:fill_out) expect(simple).to_not transition_from(:authorised).to(:filled_out).on_event(:fill_out) end it "works for multiple state machines" do expect(multiple).to transition_from(:standing).to(:walking).on_event(:walk).on(:move) expect(multiple).to_not transition_from(:standing).to(:running).on_event(:walk).on(:move) expect(multiple).to_not transition_from(:running).to(:walking).on_event(:walk).on(:move) expect(multiple).to transition_from(:sleeping).to(:processing).on_event(:start).on(:work) expect(multiple).to_not transition_from(:sleeping).to(:sleeping).on_event(:start).on(:work) expect(multiple).to_not transition_from(:processing).to(:sleeping).on_event(:start).on(:work) end end describe 'allow_transition_to' do it "works for simple state machines" do expect(simple).to allow_transition_to(:filled_out) expect(simple).to_not allow_transition_to(:authorised) end it "works for multiple state machines" do expect(multiple).to allow_transition_to(:walking).on(:move) expect(multiple).to_not allow_transition_to(:standing).on(:move) expect(multiple).to allow_transition_to(:processing).on(:work) expect(multiple).to_not allow_transition_to(:sleeping).on(:work) end end describe "have_state" do it "works for simple state machines" do expect(simple).to have_state :initialised expect(simple).to_not have_state :filled_out simple.fill_out expect(simple).to have_state :filled_out end it "works for multiple state machines" do expect(multiple).to have_state(:standing).on(:move) expect(multiple).to_not have_state(:walking).on(:move) multiple.walk expect(multiple).to have_state(:walking).on(:move) expect(multiple).to have_state(:sleeping).on(:work) expect(multiple).to_not have_state(:processing).on(:work) multiple.start expect(multiple).to have_state(:processing).on(:work) end end describe "allow_event" do it "works for simple state machines" do expect(simple).to allow_event :fill_out expect(simple).to_not allow_event :authorise simple.fill_out expect(simple).to allow_event :authorise end it "works with custom arguments" do example = SimpleExampleWithGuardArgs.new expect(example).to allow_event(:fill_out_with_args).with(true) expect(example).to_not allow_event(:fill_out_with_args).with(false) end it "works for multiple state machines" do expect(multiple).to allow_event(:walk).on(:move) expect(multiple).to_not allow_event(:hold).on(:move) multiple.walk expect(multiple).to allow_event(:hold).on(:move) expect(multiple).to allow_event(:start).on(:work) expect(multiple).to_not allow_event(:stop).on(:work) multiple.start expect(multiple).to allow_event(:stop).on(:work) end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/simple_multiple_example_spec.rb
spec/unit/simple_multiple_example_spec.rb
require 'spec_helper' describe 'state machine' do let(:simple) { SimpleMultipleExample.new } it 'starts with an initial state' do expect(simple.aasm(:move).current_state).to eq(:standing) expect(simple).to respond_to(:standing?) expect(simple).to be_standing expect(simple.aasm(:work).current_state).to eq(:sleeping) expect(simple).to respond_to(:sleeping?) expect(simple).to be_sleeping end it 'allows transitions to other states' do expect(simple).to respond_to(:walk) expect(simple).to respond_to(:walk!) simple.walk! expect(simple).to respond_to(:walking?) expect(simple).to be_walking expect(simple).to respond_to(:run) expect(simple).to respond_to(:run!) simple.run expect(simple).to respond_to(:running?) expect(simple).to be_running expect(simple).to respond_to(:start) expect(simple).to respond_to(:start!) simple.start expect(simple).to respond_to(:processing?) expect(simple).to be_processing end it 'denies transitions to other states' do expect {simple.hold}.to raise_error(AASM::InvalidTransition) expect {simple.hold!}.to raise_error(AASM::InvalidTransition) simple.walk expect {simple.walk}.to raise_error(AASM::InvalidTransition) expect {simple.walk!}.to raise_error(AASM::InvalidTransition) simple.run expect {simple.walk}.to raise_error(AASM::InvalidTransition) expect {simple.walk!}.to raise_error(AASM::InvalidTransition) expect {simple.stop}.to raise_error(AASM::InvalidTransition) expect {simple.stop!}.to raise_error(AASM::InvalidTransition) simple.start expect {simple.start}.to raise_error(AASM::InvalidTransition) expect {simple.start!}.to raise_error(AASM::InvalidTransition) simple.stop end it 'defines constants for each state name' do expect(SimpleMultipleExample::STATE_STANDING).to eq(:standing) expect(SimpleMultipleExample::STATE_WALKING).to eq(:walking) expect(SimpleMultipleExample::STATE_RUNNING).to eq(:running) expect(SimpleMultipleExample::STATE_SLEEPING).to eq(:sleeping) expect(SimpleMultipleExample::STATE_PROCESSING).to eq(:processing) expect(SimpleMultipleExample::STATE_RUNNING).to eq(:running) end context 'triggers binding_events in bindind_state_machine' do it 'does persist' do expect(simple).to be_sleeping expect(simple).to be_answered expect(simple).to receive(:start!).and_call_original simple.ask! expect(simple).to be_asked expect(simple).to be_processing expect(simple).to receive(:stop!).and_call_original simple.answer! expect(simple).to be_sleeping expect(simple).to be_answered end it 'does not persist' do expect(simple).to be_sleeping expect(simple).to be_answered expect(simple).to receive(:start).and_call_original simple.ask expect(simple).to be_asked expect(simple).to be_processing expect(simple).to receive(:stop).and_call_original simple.answer expect(simple).to be_sleeping expect(simple).to be_answered end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/localizer_spec.rb
spec/unit/localizer_spec.rb
require 'spec_helper' if defined?(ActiveRecord) require 'models/active_record/localizer_test_model' load_schema describe AASM::Localizer, "new style" do before(:all) do I18n.load_path << 'spec/localizer_test_model_new_style.yml' I18n.reload! end after(:all) do I18n.load_path.delete('spec/localizer_test_model_new_style.yml') I18n.backend.load_translations end let (:foo_opened) { LocalizerTestModel.new } let (:foo_closed) { LocalizerTestModel.new.tap { |x| x.aasm_state = :closed } } context 'aasm.human_state' do it 'should return translated state value' do expect(foo_opened.aasm.human_state).to eq("It's open now!") end it 'should return humanized value if not localized' do expect(foo_closed.aasm.human_state).to eq("Closed") end end context 'aasm.human_event_name' do context 'with event name' do it 'should return translated event name' do expect(LocalizerTestModel.aasm.human_event_name(:close)).to eq("Let's close it!") end it 'should return humanized event name' do expect(LocalizerTestModel.aasm.human_event_name(:open)).to eq("Open") end end context 'with event object' do it 'should return translated event name' do event = LocalizerTestModel.aasm.events.detect { |e| e.name == :close } expect(LocalizerTestModel.aasm.human_event_name(event)).to eq("Let's close it!") end it 'should return humanized event name' do event = LocalizerTestModel.aasm.events.detect { |e| e.name == :open } expect(LocalizerTestModel.aasm.human_event_name(event)).to eq("Open") end end end end describe AASM::Localizer, "deprecated style" do before(:all) do I18n.load_path << 'spec/localizer_test_model_deprecated_style.yml' I18n.reload! I18n.backend.load_translations end after(:all) do I18n.load_path.delete('spec/localizer_test_model_deprecated_style.yml') I18n.backend.load_translations end let (:foo_opened) { LocalizerTestModel.new } let (:foo_closed) { LocalizerTestModel.new.tap { |x| x.aasm_state = :closed } } context 'aasm.human_state' do it 'should return translated state value' do expect(foo_opened.aasm.human_state).to eq("It's open now!") end it 'should return humanized value if not localized' do expect(foo_closed.aasm.human_state).to eq("Closed") end end context 'aasm.human_event_name' do context 'with event name' do it 'should return translated event name' do expect(LocalizerTestModel.aasm.human_event_name(:close)).to eq("Let's close it!") end it 'should return humanized event name' do expect(LocalizerTestModel.aasm.human_event_name(:open)).to eq("Open") end end context 'with event object' do it 'should return translated event name' do event = LocalizerTestModel.aasm.events.detect { |e| e.name == :close } expect(LocalizerTestModel.aasm.human_event_name(event)).to eq("Let's close it!") end it 'should return humanized event name' do event = LocalizerTestModel.aasm.events.detect { |e| e.name == :open } expect(LocalizerTestModel.aasm.human_event_name(event)).to eq("Open") end end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/event_with_keyword_arguments_spec.rb
spec/unit/event_with_keyword_arguments_spec.rb
require 'spec_helper' describe EventWithKeywordArguments do let(:example) { EventWithKeywordArguments.new } context 'when using required keyword arguments' do it 'works with required keyword argument' do expect(example.close(key: 1)).to be_truthy end it 'works when required keyword argument is nil' do expect(example.close(key: nil)).to be_truthy end it 'fails when the required keyword argument is not provided' do expect { example.close() }.to raise_error(ArgumentError) end end context 'when mixing positional and keyword arguments' do it 'works with defined keyword arguments' do expect(example.another_close(1, key: 2)).to be_truthy end it 'works when optional keyword argument is nil' do expect(example.another_close(1, key: nil)).to be_truthy end it 'works when optional keyword argument is not provided' do expect(example.another_close(1)).to be_truthy end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/complex_multiple_example_spec.rb
spec/unit/complex_multiple_example_spec.rb
require 'spec_helper' describe 'on initialization' do let(:auth) {ComplexExampleMultiple.new} it 'should be in the initial state' do expect(auth.aasm(:left).current_state).to eq(:pending) expect(auth.aasm(:right).current_state).to eq(:pending) end it 'should have an activation code' do expect(auth.has_activation_code?).to be_truthy expect(auth.activation_code).to eq '12' end end describe 'when being unsuspended' do let(:auth) {ComplexExampleMultiple.new} it 'should be able to unsuspend' do auth.left_activate! auth.left_suspend! expect(auth.may_left_unsuspend?).to be true auth.right_activate! auth.right_suspend! expect(auth.may_right_unsuspend?).to be true end it 'should not be able to unsuspend into active' do auth.left_suspend! expect(auth.may_left_unsuspend?(:active)).not_to be true auth.right_activate! auth.right_suspend! expect(auth.may_right_unsuspend?(:active)).to be true end it 'should be able to wait into waiting if polite' do auth.left_suspend! expect(auth.may_left_wait?(:waiting, :please)).to be true auth.left_wait!(:please) auth.right_suspend! expect(auth.may_right_wait?(:waiting)).to be false auth.right_wait!(:please) end it 'should not be able to be unsuspended into active if not polite' do auth.left_suspend! expect(auth.may_left_wait?(:waiting)).not_to be true expect(auth.may_left_wait?(:waiting, :rude)).not_to be true expect {auth.left_wait!(:rude)}.to raise_error(AASM::InvalidTransition) expect {auth.left_wait!}.to raise_error(AASM::InvalidTransition) end it 'should not be able to be unpassified' do auth.left_activate! auth.left_suspend! auth.left_unsuspend! expect(auth.may_left_unpassify?).not_to be true expect {auth.left_unpassify!}.to raise_error(AASM::InvalidTransition) end it 'should be active if previously activated' do auth.left_activate! auth.left_suspend! auth.left_unsuspend! expect(auth.aasm(:left).current_state).to eq(:active) end it 'should be pending if not previously activated, but an activation code is present' do auth.left_suspend! auth.left_unsuspend! expect(auth.aasm(:left).current_state).to eq(:pending) end it 'should be passive if not previously activated and there is no activation code' do auth.activation_code = nil auth.left_suspend! auth.left_unsuspend! expect(auth.aasm(:left).current_state).to eq(:passive) end it "should be able to fire known events" do expect(auth.aasm(:left).may_fire_event?(:left_activate)).to be true expect(auth.aasm(:right).may_fire_event?(:right_activate)).to be true end it 'should not be able to fire unknown events' do expect(auth.aasm(:left).may_fire_event?(:unknown)).to be false expect(auth.aasm(:right).may_fire_event?(:unknown)).to be false end it 'should be able to fire event by name' do expect(auth.aasm(:left).fire(:left_activate)).to be true expect(auth.aasm(:left).current_state).to eq(:active) expect(auth.aasm(:right).fire(:right_activate)).to be true expect(auth.aasm(:right).current_state).to eq(:active) end it 'should be able to fire! event by name' do expect(auth.aasm(:left).fire!(:left_activate)).to be true expect(auth.aasm(:left).current_state).to eq(:active) expect(auth.aasm(:right).fire!(:right_activate)).to be true expect(auth.aasm(:right).current_state).to eq(:active) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/subclassing_multiple_spec.rb
spec/unit/subclassing_multiple_spec.rb
require 'spec_helper' describe 'subclassing with multiple state machines' do it 'should have the parent states' do SuperClassMultiple.aasm(:left).states.each do |state| expect(SubClassWithMoreStatesMultiple.aasm(:left).states).to include(state) end expect(SubClassMultiple.aasm(:left).states).to eq(SuperClassMultiple.aasm(:left).states) SuperClassMultiple.aasm(:right).states.each do |state| expect(SubClassWithMoreStatesMultiple.aasm(:right).states).to include(state) end expect(SubClassMultiple.aasm(:right).states).to eq(SuperClassMultiple.aasm(:right).states) end it 'should not add the child states to the parent machine' do expect(SuperClassMultiple.aasm(:left).states).not_to include(:foo) expect(SuperClassMultiple.aasm(:right).states).not_to include(:archived) end it 'should have the same events as its parent' do expect(SubClassMultiple.aasm(:left).events).to eq(SuperClassMultiple.aasm(:left).events) expect(SubClassMultiple.aasm(:right).events).to eq(SuperClassMultiple.aasm(:right).events) end it 'should know how to respond to question methods' do expect(SubClassMultiple.new.may_foo?).to be_truthy expect(SubClassMultiple.new.may_close?).to be_truthy end it 'should not break if I call methods from super class' do son = SubClassMultiple.new son.update_state expect(son.aasm(:left).current_state).to eq(:ended) end it 'should allow the child to modify its left state machine' do son = SubClassMultiple.new expect(son.left_called_after).to eq(nil) expect(son.right_called_after).to eq(nil) son.foo expect(son.left_called_after).to eq(true) expect(son.right_called_after).to eq(nil) global_callbacks = SubClassMultiple.aasm(:left).state_machine.global_callbacks expect(global_callbacks).to_not be_empty expect(global_callbacks[:after_all_transitions]).to eq :left_after_all_event end it 'should allow the child to modify its right state machine' do son = SubClassMultiple.new expect(son.right_called_after).to eq(nil) expect(son.left_called_after).to eq(nil) son.close expect(son.right_called_after).to eq(true) expect(son.left_called_after).to eq(nil) global_callbacks = SubClassMultiple.aasm(:right).state_machine.global_callbacks expect(global_callbacks).to_not be_empty expect(global_callbacks[:after_all_transitions]).to eq :right_after_all_event end it 'should not modify the parent left state machine' do super_class_event = SuperClassMultiple.aasm(:left).events.select { |event| event.name == :foo }.first expect(super_class_event.options).to be_empty expect(SuperClassMultiple.aasm(:left).state_machine.global_callbacks).to be_empty end it 'should not modify the parent right state machine' do super_class_event = SuperClassMultiple.aasm(:right).events.select { |event| event.name == :close }.first expect(super_class_event.options).to be_empty expect(SuperClassMultiple.aasm(:right).state_machine.global_callbacks).to be_empty end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/event_naming_spec.rb
spec/unit/event_naming_spec.rb
require 'spec_helper' describe "event naming" do let(:state_machine) { StateMachineWithFailedEvent.new } it "allows an event of failed without blowing the stack aka stack level too deep" do state_machine.failed expect { state_machine.failed }.to raise_error(AASM::InvalidTransition) end it "allows send as event name" do expect(state_machine.aasm.current_state).to eq :init state_machine.send expect(state_machine.aasm.current_state).to eq :sent end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_multiple_spec.rb
spec/unit/guard_multiple_spec.rb
require 'spec_helper' describe "per-transition guards" do let(:guardian) { GuardianMultiple.new } it "allows the transition if the guard succeeds" do expect { guardian.use_one_guard_that_succeeds! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the guard fails" do expect { guardian.use_one_guard_that_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "allows the transition if all guards succeeds" do expect { guardian.use_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the first guard fails" do expect { guardian.use_guards_where_the_first_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the second guard fails" do expect { guardian.use_guards_where_the_second_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end end describe "event guards" do let(:guardian) { GuardianMultiple.new } it "allows the transition if the event guards succeed" do expect { guardian.use_event_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "allows the transition if the event and transition guards succeed" do expect { guardian.use_event_and_transition_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the first event guard fails" do expect { guardian.use_event_guards_where_the_first_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the second event guard fails" do expect { guardian.use_event_guards_where_the_second_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the transition guard fails" do expect { guardian.use_event_and_transition_guards_where_third_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/readme_spec.rb
spec/unit/readme_spec.rb
require 'spec_helper' describe 'testing the README examples' do it 'Usage' do class Job include AASM aasm do state :sleeping, :initial => true state :running, :cleaning event :run do transitions :from => :sleeping, :to => :running end event :clean do transitions :from => :running, :to => :cleaning end event :sleep do transitions :from => [:running, :cleaning], :to => :sleeping end end end job = Job.new expect(job.sleeping?).to eql true expect(job.may_run?).to eql true job.run expect(job.running?).to eql true expect(job.sleeping?).to eql false expect(job.may_run?).to eql false expect { job.run }.to raise_error(AASM::InvalidTransition) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_without_from_specified_spec.rb
spec/unit/guard_without_from_specified_spec.rb
require 'spec_helper' describe "transitions without from specified" do let(:guardian) { GuardianWithoutFromSpecified.new } it "allows the transitions if guard succeeds" do expect { guardian.use_guards_where_the_first_fails! }.to_not raise_error expect(guardian).to be_gamma end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/states_on_one_line_example_spec.rb
spec/unit/states_on_one_line_example_spec.rb
require 'spec_helper' describe StatesOnOneLineExample do let(:example) { StatesOnOneLineExample.new } describe 'on initialize' do it 'should be in the initial state' do expect(example.aasm(:one_line).current_state).to eql :initial end end describe 'states' do it 'should have all 3 states defined' do expect(example.aasm(:one_line).states.map(&:name)).to eq [:initial, :first, :second] end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/state_spec.rb
spec/unit/state_spec.rb
require 'spec_helper' describe AASM::Core::State do let(:state_machine) { AASM::StateMachine.new(:name) } before(:each) do @name = :astate @options = { :crazy_custom_key => 'key' } end def new_state(options={}) AASM::Core::State.new(@name, Conversation, state_machine, @options.merge(options)) end it 'should set the name' do state = new_state expect(state.name).to eq(:astate) end describe '#display_name' do subject(:display_name) { new_state(options).display_name } context 'without options' do let(:options) { {} } context 'without I18n' do before { allow(Module).to receive(:const_defined?).with(:I18n).and_return(nil) } it 'should set the display_name from name' do expect(display_name).to eq('Astate') end end end context 'with :display option' do let(:options) { { display: "A State" } } it 'should set the display_name from options' do expect(display_name).to eq('A State') end end end it 'should set the options and expose them as options' do expect(new_state.options).to eq(@options) end it 'should be equal to a symbol of the same name' do expect(new_state).to eq(:astate) end it 'should be equal to a State of the same name' do expect(new_state).to eq(new_state) end it 'should send a message to the record for an action if the action is present as a symbol' do state = new_state(:entering => :foo) record = double('record') expect(record).to receive(:foo) state.fire_callbacks(:entering, record) end it 'should send a message to the record for an action if the action is present as a string' do state = new_state(:entering => 'foo') record = double('record') expect(record).to receive(:foo) state.fire_callbacks(:entering, record) end it 'should send a message to the record for each action' do state = new_state(:entering => [:a, :b, "c", lambda {|r| r.foobar }]) record = double('record') expect(record).to receive(:a) expect(record).to receive(:b) expect(record).to receive(:c) expect(record).to receive(:foobar) state.fire_callbacks(:entering, record, record) end it "should stop calling actions if one of them raises :halt_aasm_chain" do state = new_state(:entering => [:a, :b, :c]) record = double('record') expect(record).to receive(:a) expect(record).to receive(:b).and_throw(:halt_aasm_chain) expect(record).not_to receive(:c) state.fire_callbacks(:entering, record) end it 'should call a proc, passing in the record for an action if the action is present' do state = new_state(:entering => Proc.new {|r| r.foobar}) record = double('record') expect(record).to receive(:foobar) state.fire_callbacks(:entering, record, record) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/event_spec.rb
spec/unit/event_spec.rb
require 'spec_helper' describe 'adding an event' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) do AASM::Core::Event.new(:close_order, state_machine, {:success => :success_callback}) do before :before_callback after :after_callback transitions :to => :closed, :from => [:open, :received], success: [:transition_success_callback] end end it 'should set the name' do expect(event.name).to eq(:close_order) end it 'should set the success callback' do expect(event.options[:success]).to eq(:success_callback) end it 'should set the after callback' do expect(event.options[:after]).to eq([:after_callback]) end it 'should set the before callback' do expect(event.options[:before]).to eq([:before_callback]) end it 'should create transitions' do transitions = event.transitions expect(transitions[0].from).to eq(:open) expect(transitions[0].to).to eq(:closed) expect(transitions[1].from).to eq(:received) expect(transitions[1].to).to eq(:closed) end end describe 'transition inspection' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) do AASM::Core::Event.new(:run, state_machine) do transitions :to => :running, :from => :sleeping end end it 'should support inspecting transitions from other states' do expect(event.transitions_from_state(:sleeping).map(&:to)).to eq([:running]) expect(event.transitions_from_state?(:sleeping)).to be_truthy expect(event.transitions_from_state(:cleaning).map(&:to)).to eq([]) expect(event.transitions_from_state?(:cleaning)).to be_falsey end it 'should support inspecting transitions to other states' do expect(event.transitions_to_state(:running).map(&:from)).to eq([:sleeping]) expect(event.transitions_to_state?(:running)).to be_truthy expect(event.transitions_to_state(:cleaning).map(&:to)).to eq([]) expect(event.transitions_to_state?(:cleaning)).to be_falsey end end describe 'transition inspection without from' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) do AASM::Core::Event.new(:run, state_machine) do transitions :to => :running end end it 'should support inspecting transitions from other states' do expect(event.transitions_from_state(:sleeping).map(&:to)).to eq([:running]) expect(event.transitions_from_state?(:sleeping)).to be_truthy expect(event.transitions_from_state(:cleaning).map(&:to)).to eq([:running]) expect(event.transitions_from_state?(:cleaning)).to be_truthy end end describe 'firing an event' do let(:state_machine) { AASM::StateMachine.new(:name) } it 'should return nil if the transitions are empty' do obj = double('object', :aasm => double('aasm', :current_state => 'open')) event = AASM::Core::Event.new(:event, state_machine) expect(event.fire(obj)).to be_nil end it 'should return the state of the first matching transition it finds' do event = AASM::Core::Event.new(:event, state_machine) do transitions :to => :closed, :from => [:open, :received] end obj = double('object', :aasm => double('aasm', :current_state => :open)) expect(event.fire(obj)).to eq(:closed) end it 'should call the guard with the params passed in' do event = AASM::Core::Event.new(:event, state_machine) do transitions :to => :closed, :from => [:open, :received], :guard => :guard_fn end obj = double('object', :aasm => double('aasm', :current_state => :open)) expect(obj).to receive(:guard_fn).with('arg1', 'arg2').and_return(true) expect(event.fire(obj, {}, 'arg1', 'arg2')).to eq(:closed) end context 'when given a gaurd proc' do it 'should have access to callback failures in the transitions' do event = AASM::Core::Event.new(:graduate, state_machine) do transitions :to => :alumni, :from => [:student, :applicant], :guard => Proc.new { 1 + 1 == 3 } end line_number = __LINE__ - 2 obj = double('object', :aasm => double('aasm', :current_state => :student)) event.fire(obj, {}) expect(event.failed_callbacks).to eq ["#{__FILE__}##{line_number}"] end end context 'when given a guard symbol' do it 'should have access to callback failures in the transitions' do event = AASM::Core::Event.new(:graduate, state_machine) do transitions :to => :alumni, :from => [:student, :applicant], guard: :paid_tuition? end obj = double('object', :aasm => double('aasm', :current_state => :student)) allow(obj).to receive(:paid_tuition?).and_return(false) event.fire(obj, {}) expect(event.failed_callbacks).to eq [:paid_tuition?] end end end describe 'should fire callbacks' do describe 'success' do it "if it's a symbol" do ThisNameBetterNotBeInUse.instance_eval { aasm do event :with_symbol, :success => :symbol_success_callback do transitions :to => :symbol, :from => [:initial] end end } model = ThisNameBetterNotBeInUse.new expect(model).to receive(:symbol_success_callback) model.with_symbol! end it "if it's a string" do ThisNameBetterNotBeInUse.instance_eval { aasm do event :with_string, :success => 'string_success_callback' do transitions :to => :string, :from => [:initial] end end } model = ThisNameBetterNotBeInUse.new expect(model).to receive(:string_success_callback) model.with_string! end it "if passed an array of strings and/or symbols" do ThisNameBetterNotBeInUse.instance_eval { aasm do event :with_array, :success => [:success_callback1, 'success_callback2'] do transitions :to => :array, :from => [:initial] end end } model = ThisNameBetterNotBeInUse.new expect(model).to receive(:success_callback1) expect(model).to receive(:success_callback2) model.with_array! end it "if passed an array of strings and/or symbols and/or procs" do ThisNameBetterNotBeInUse.instance_eval { aasm do event :with_array_including_procs, :success => [:success_callback1, 'success_callback2', lambda { proc_success_callback }] do transitions :to => :array, :from => [:initial] end end } model = ThisNameBetterNotBeInUse.new expect(model).to receive(:success_callback1) expect(model).to receive(:success_callback2) expect(model).to receive(:proc_success_callback) model.with_array_including_procs! end it "if it's a proc" do ThisNameBetterNotBeInUse.instance_eval { aasm do event :with_proc, :success => lambda { proc_success_callback } do transitions :to => :proc, :from => [:initial] end end } model = ThisNameBetterNotBeInUse.new expect(model).to receive(:proc_success_callback) model.with_proc! end end describe 'after' do it "if they set different ways" do ThisNameBetterNotBeInUse.instance_eval do aasm do event :with_afters, :after => :do_one_thing_after do after do do_another_thing_after_too end after do do_third_thing_at_last end transitions :to => :proc, :from => [:initial] end end end model = ThisNameBetterNotBeInUse.new expect(model).to receive(:do_one_thing_after).once.ordered expect(model).to receive(:do_another_thing_after_too).once.ordered expect(model).to receive(:do_third_thing_at_last).once.ordered model.with_afters! end end describe 'before' do it "if it's a proc" do ThisNameBetterNotBeInUse.instance_eval do aasm do event :before_as_proc do before do do_something_before end transitions :to => :proc, :from => [:initial] end end end model = ThisNameBetterNotBeInUse.new expect(model).to receive(:do_something_before).once model.before_as_proc! end end it 'in right order' do ThisNameBetterNotBeInUse.instance_eval do aasm do event :in_right_order, :after => :do_something_after do before do do_something_before end transitions :to => :proc, :from => [:initial] end end end model = ThisNameBetterNotBeInUse.new expect(model).to receive(:do_something_before).once.ordered expect(model).to receive(:do_something_after).once.ordered model.in_right_order! end end describe 'current event' do let(:pe) {ParametrisedEvent.new} it 'if no event has been triggered' do expect(pe.aasm.current_event).to be_nil end it 'if a event has been triggered' do pe.wakeup expect(pe.aasm.current_event).to eql :wakeup end it 'if no event has been triggered' do pe.wakeup! expect(pe.aasm.current_event).to eql :wakeup! end describe "when calling events with fire/fire!" do context "fire" do it "should populate aasm.current_event and transition (sleeping to showering)" do pe.aasm.fire(:wakeup) expect(pe.aasm.current_event).to eq :wakeup expect(pe.aasm.current_state).to eq :showering end it "should allow event names as strings" do pe.aasm.fire("wakeup") expect(pe.aasm.current_event).to eq :wakeup expect(pe.aasm.current_state).to eq :showering end end context "fire!" do it "should populate aasm.current_event and transition (sleeping to showering)" do pe.aasm.fire!(:wakeup) expect(pe.aasm.current_event).to eq :wakeup! expect(pe.aasm.current_state).to eq :showering end it "should allow event names as strings" do pe.aasm.fire!("wakeup") expect(pe.aasm.current_event).to eq :wakeup! expect(pe.aasm.current_state).to eq :showering end end end end describe 'parametrised events' do let(:pe) {ParametrisedEvent.new} it 'should transition to specified next state (sleeping to showering)' do pe.wakeup!(:showering) expect(pe.aasm.current_state).to eq(:showering) end it 'should transition to specified next state (sleeping to working)' do pe.wakeup!(:working) expect(pe.aasm.current_state).to eq(:working) end it 'should transition to default (first or showering) state' do pe.wakeup! expect(pe.aasm.current_state).to eq(:showering) end it 'should transition to default state when :after transition invoked' do pe.dress!('purple', 'dressy') expect(pe.aasm.current_state).to eq(:working) end it 'should call :after transition method with args' do pe.wakeup!(:showering) expect(pe).to receive(:wear_clothes).with('blue', 'jeans') pe.dress!(:working, 'blue', 'jeans') end it 'should call :after transition method if arg is nil' do dryer = nil expect(pe).to receive(:wet_hair).with(dryer) pe.shower!(dryer) end it 'should call :after transition proc' do pe.wakeup!(:showering) expect(pe).to receive(:wear_clothes).with('purple', 'slacks') pe.dress!(:dating, 'purple', 'slacks') end it 'should call :after transition with an array of methods' do pe.wakeup!(:showering) expect(pe).to receive(:condition_hair) expect(pe).to receive(:fix_hair) pe.dress!(:prettying_up) end it 'should call :success transition method with args' do pe.wakeup!(:showering) expect(pe).to receive(:wear_makeup).with('foundation', 'SPF') pe.dress!(:working, 'foundation', 'SPF') end it 'should call :success transition method if arg is nil' do shirt_color = nil expect(pe).to receive(:wear_clothes).with(shirt_color) pe.shower!(shirt_color) end it 'should call :success transition proc' do pe.wakeup!(:showering) expect(pe).to receive(:wear_makeup).with('purple', 'slacks') pe.dress!(:dating, 'purple', 'slacks') end it 'should call :success transition with an array of methods' do pe.wakeup!(:showering) expect(pe).to receive(:touch_up_hair) pe.dress!(:prettying_up) end end describe 'event firing without persistence' do it 'should attempt to persist if aasm_write_state is defined' do foo = Foo.new def foo.aasm_write_state; end expect(foo).to be_open expect(foo).to receive(:aasm_write_state_without_persistence) foo.close end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/basic_two_state_machines_example_spec.rb
spec/unit/basic_two_state_machines_example_spec.rb
require 'spec_helper' describe 'on initialization' do let(:example) { BasicTwoStateMachinesExample.new } it 'should be in the initial state' do expect(example.aasm(:search).current_state).to eql :initialised expect(example.aasm(:sync).current_state).to eql :unsynced end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/event_multiple_spec.rb
spec/unit/event_multiple_spec.rb
require 'spec_helper' describe 'current event' do let(:pe) {ParametrisedEventMultiple.new} it 'if no event has been triggered' do expect(pe.aasm(:left).current_event).to be_nil end it 'if a event has been triggered' do pe.wakeup expect(pe.aasm(:left).current_event).to eql :wakeup end it 'if no event has been triggered' do pe.wakeup! expect(pe.aasm(:left).current_event).to eql :wakeup! end end describe 'parametrised events' do let(:pe) {ParametrisedEventMultiple.new} it 'should transition to specified next state (sleeping to showering)' do pe.wakeup!(:showering) expect(pe.aasm(:left).current_state).to eq(:showering) end it 'should transition to specified next state (sleeping to working)' do pe.wakeup!(:working) expect(pe.aasm(:left).current_state).to eq(:working) end it 'should transition to default (first or showering) state' do pe.wakeup! expect(pe.aasm(:left).current_state).to eq(:showering) end it 'should transition to default state when :after transition invoked' do pe.dress!('purple', 'dressy') expect(pe.aasm(:left).current_state).to eq(:working) end it 'should call :after transition method with args' do pe.wakeup!(:showering) expect(pe).to receive(:wear_clothes).with('blue', 'jeans') pe.dress!(:working, 'blue', 'jeans') end it 'should call :after transition proc' do pe.wakeup!(:showering) expect(pe).to receive(:wear_clothes).with('purple', 'slacks') pe.dress!(:dating, 'purple', 'slacks') end it 'should call :after transition with an array of methods' do pe.wakeup!(:showering) expect(pe).to receive(:condition_hair) expect(pe).to receive(:fix_hair) pe.dress!(:prettying_up) end end describe 'event firing without persistence' do it 'should attempt to persist if aasm_write_state is defined' do foo = Foo.new def foo.aasm_write_state; end expect(foo).to be_open expect(foo).to receive(:aasm_write_state_without_persistence) foo.close end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_arguments_check_spec.rb
spec/unit/guard_arguments_check_spec.rb
require 'spec_helper' describe "nil as first argument" do let(:guard) { GuardArgumentsCheck.new } it 'does not raise errors' do expect { guard.mark_as_reviewed(nil, 'second arg') }.not_to raise_error end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/memory_leak_spec.rb
spec/unit/memory_leak_spec.rb
# require 'spec_helper' # describe "state machines" do # def number_of_objects(klass) # ObjectSpace.each_object(klass) {} # end # def machines # AASM::StateMachineStore.instance_variable_get("@stores") # end # it "should be created without memory leak" do # machines_count = machines.size # state_count = number_of_objects(AASM::Core::State) # event_count = number_of_objects(AASM::Core::Event) # puts "event_count = #{event_count}" # transition_count = number_of_objects(AASM::Core::Transition) # load File.expand_path(File.dirname(__FILE__) + '/../models/not_auto_loaded/process.rb') # machines.size.should == machines_count + 1 # + Process # number_of_objects(Models::Process).should == 0 # number_of_objects(AASM::Core::State).should == state_count + 3 # + Process # puts "event_count = #{number_of_objects(AASM::Core::Event)}" # number_of_objects(AASM::Core::Event).should == event_count + 2 # + Process # number_of_objects(AASM::Core::Transition).should == transition_count + 2 # + Process # Models.send(:remove_const, "Process") if Models.const_defined?("Process") # load File.expand_path(File.dirname(__FILE__) + '/../models/not_auto_loaded/process.rb') # machines.size.should == machines_count + 1 # + Process # number_of_objects(AASM::Core::State).should == state_count + 3 # + Process # # ObjectSpace.each_object(AASM::Core::Event) {|o| puts o.inspect} # puts "event_count = #{number_of_objects(AASM::Core::Event)}" # number_of_objects(AASM::Core::Event).should == event_count + 2 # + Process # number_of_objects(AASM::Core::Transition).should == transition_count + 2 # + Process # end # end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/simple_example_spec.rb
spec/unit/simple_example_spec.rb
require 'spec_helper' describe 'state machine' do let(:simple) { SimpleExample.new } it 'starts with an initial state' do expect(simple.aasm.current_state).to eq(:initialised) expect(simple).to respond_to(:initialised?) expect(simple).to be_initialised end it 'allows transitions to other states' do expect(simple).to respond_to(:fill_out) expect(simple).to respond_to(:fill_out!) simple.fill_out! expect(simple).to respond_to(:filled_out?) expect(simple).to be_filled_out expect(simple).to respond_to(:authorise) expect(simple).to respond_to(:authorise!) simple.authorise expect(simple).to respond_to(:authorised?) expect(simple).to be_authorised end it 'shows the permitted transitions' do expect(simple.aasm.permitted_transitions).to eq( [ { event: :fill_out, state: :filled_out }, { event: :deny, state: :denied } ] ) simple.fill_out! expect(simple.aasm.permitted_transitions).to eq([{ event: :authorise, state: :authorised }]) simple.authorise expect(simple.aasm.permitted_transitions).to eq([]) end it 'denies transitions to other states' do expect {simple.authorise}.to raise_error(AASM::InvalidTransition) expect {simple.authorise!}.to raise_error(AASM::InvalidTransition) simple.fill_out expect {simple.fill_out}.to raise_error(AASM::InvalidTransition) expect {simple.fill_out!}.to raise_error(AASM::InvalidTransition) simple.authorise expect {simple.fill_out}.to raise_error(AASM::InvalidTransition) expect {simple.fill_out!}.to raise_error(AASM::InvalidTransition) end it 'defines constants for each state name' do expect(SimpleExample::STATE_INITIALISED).to eq(:initialised) expect(SimpleExample::STATE_FILLED_OUT).to eq(:filled_out) expect(SimpleExample::STATE_AUTHORISED).to eq(:authorised) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/new_dsl_spec.rb
spec/unit/new_dsl_spec.rb
require 'spec_helper' describe "the new dsl" do let(:process) {ProcessWithNewDsl.new} it 'should not conflict with other event or state methods' do expect {ProcessWithNewDsl.state}.to raise_error(RuntimeError, "wrong state method") expect {ProcessWithNewDsl.event}.to raise_error(RuntimeError, "wrong event method") end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/abstract_class_spec.rb
spec/unit/abstract_class_spec.rb
require 'spec_helper' if defined?(ActiveRecord) require 'models/active_record/person' load_schema describe 'Abstract subclassing' do it 'should have the parent states' do Person.aasm.states.each do |state| expect(Base.aasm.states).to include(state) end expect(Person.aasm.states).to eq(Base.aasm.states) end it 'should have the same events as its parent' do expect(Base.aasm.events).to eq(Person.aasm.events) end it 'should not break aasm methods when super class is abstract_class' do person = Person.new person.status = 'active' person.deactivate! expect(person.aasm.current_state).to eq(:inactive) end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/reloading_spec.rb
spec/unit/reloading_spec.rb
require 'spec_helper' describe 'when redefining states' do let(:definer) { DoubleDefiner.new } it "allows extending states" do expect(definer).to receive(:do_enter) definer.finish end it "allows extending events" do expect(definer).to receive(:do_on_transition) definer.finish end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/override_warning_spec.rb
spec/unit/override_warning_spec.rb
require 'spec_helper' describe 'warns when overrides a method' do before do AASM::Configuration.hide_warnings = false end after do AASM::Configuration.hide_warnings = true end module Clumsy def self.included base base.send :include, AASM base.aasm do state :valid event(:save) { } end end end module WithEnumBase def self.included base base.send :include, AASM base.instance_eval do def defined_enums { 'state' => { 'valid' => 0, 'invalid' => 1 } } end end base.aasm enum: true do state :valid event(:save) { } end end end describe 'state' do let(:base_klass) do Class.new do def valid?; end end end subject { base_klass.send :include, Clumsy } it 'should log to warn' do expect_any_instance_of(Logger).to receive(:warn).with(": overriding method 'valid?'!") subject end end describe 'enum' do let(:enum_base_klass) do Class.new do def valid?; end end end subject { enum_base_klass.send :include, WithEnumBase } it 'should not log to warn' do expect_any_instance_of(Logger).to receive(:warn).never subject end end describe 'event' do context 'may?' do let(:base_klass) do Class.new do def may_save?; end def save!; end def save; end end end subject { base_klass.send :include, Clumsy } it 'should log to warn' do expect_any_instance_of(Logger).to receive(:warn).exactly(3).times do |logger, message| expect( [ ": overriding method 'may_save?'!", ": overriding method 'save!'!", ": overriding method 'save'!" ] ).to include(message) end subject end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/guard_spec.rb
spec/unit/guard_spec.rb
require 'spec_helper' describe "per-transition guards" do let(:guardian) { Guardian.new } it "allows the transition if the guard succeeds" do expect { guardian.use_one_guard_that_succeeds! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the guard fails" do expect { guardian.use_one_guard_that_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "allows the transition if all guards succeeds" do expect { guardian.use_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the first guard fails" do expect { guardian.use_guards_where_the_first_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the second guard fails" do expect { guardian.use_guards_where_the_second_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end describe "with params" do it "using a Proc" do expect(guardian).to receive(:inner_guard).with({:flag => true}).and_return(true) guardian.use_proc_guard_with_params(:flag => true) end it "using a lambda" do expect(guardian).to receive(:inner_guard).with({:flag => true}).and_return(true) guardian.use_lambda_guard_with_params(:flag => true) end end end describe "event guards" do let(:guardian) { Guardian.new } it "allows the transition if the event guards succeed" do expect { guardian.use_event_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "allows the transition if the event and transition guards succeed" do expect { guardian.use_event_and_transition_guards_that_succeed! }.to_not raise_error expect(guardian).to be_beta end it "stops the transition if the first event guard fails" do expect { guardian.use_event_guards_where_the_first_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the second event guard fails" do expect { guardian.use_event_guards_where_the_second_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end it "stops the transition if the transition guard fails" do expect { guardian.use_event_and_transition_guards_where_third_fails! }.to raise_error(AASM::InvalidTransition) expect(guardian).to be_alpha end end if defined?(ActiveRecord) Dir[File.dirname(__FILE__) + "/../models/active_record/*.rb"].sort.each do |f| require File.expand_path(f) end load_schema describe "ActiveRecord per-transition guards" do let(:example) { ComplexActiveRecordExample.new } it "should be able to increment" do expect(example.may_increment?).to be true end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/transition_spec.rb
spec/unit/transition_spec.rb
require 'spec_helper' describe 'transitions' do it 'should raise an exception when whiny' do process = ProcessWithNewDsl.new 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 it 'should not raise an exception when not whiny' do silencer = Silencer.new expect(silencer.smile!).to be_falsey expect(silencer).to be_silent end it 'should not raise an exception when superclass not whiny' do sub = SubClassing.new expect(sub.smile!).to be_falsey expect(sub).to be_silent end it 'should not raise an exception when from is nil even if whiny' do silencer = Silencer.new expect(silencer.smile_any!).to be_truthy expect(silencer).to be_smiling end it 'should call the block on success' do silencer = Silencer.new success = false expect { silencer.smile_any! do success = true end }.to change { success }.to(true) end it 'should not call the block on failure' do silencer = Silencer.new success = false expect { silencer.smile! do success = true end }.not_to change { success } end end describe AASM::Core::Transition do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } it 'should set from, to, and opts attr readers' do opts = {:from => 'foo', :to => 'bar', :guard => 'g'} st = AASM::Core::Transition.new(event, opts) expect(st.from).to eq(opts[:from]) expect(st.to).to eq(opts[:to]) expect(st.opts).to eq(opts) end it 'should set on_transition with deprecation warning' do opts = {:from => 'foo', :to => 'bar'} st = AASM::Core::Transition.allocate expect(st).to receive(:warn).with('[DEPRECATION] :on_transition is deprecated, use :after instead') st.send :initialize, event, opts do guard :gg on_transition :after_callback end expect(st.opts[:after]).to eql [:after_callback] end it 'should set after, guard and success from dsl' do opts = {:from => 'foo', :to => 'bar', :guard => 'g'} st = AASM::Core::Transition.new(event, opts) do guard :gg after :after_callback success :after_persist end expect(st.opts[:guard]).to eql ['g', :gg] expect(st.opts[:after]).to eql [:after_callback] # TODO fix this bad code coupling expect(st.opts[:success]).to eql [:after_persist] # TODO fix this bad code coupling end it 'should pass equality check if from and to are the same' do opts = {:from => 'foo', :to => 'bar', :guard => 'g'} st = AASM::Core::Transition.new(event, opts) obj = double('object') allow(obj).to receive(:from).and_return(opts[:from]) allow(obj).to receive(:to).and_return(opts[:to]) expect(st).to eq(obj) end it 'should fail equality check if from are not the same' do opts = {:from => 'foo', :to => 'bar', :guard => 'g'} st = AASM::Core::Transition.new(event, opts) obj = double('object') allow(obj).to receive(:from).and_return('blah') allow(obj).to receive(:to).and_return(opts[:to]) expect(st).not_to eq(obj) end it 'should fail equality check if to are not the same' do opts = {:from => 'foo', :to => 'bar', :guard => 'g'} st = AASM::Core::Transition.new(event, opts) obj = double('object') allow(obj).to receive(:from).and_return(opts[:from]) allow(obj).to receive(:to).and_return('blah') expect(st).not_to eq(obj) end end describe AASM::Core::Transition, '- when performing guard checks' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } it 'should return true of there is no guard' do opts = {:from => 'foo', :to => 'bar'} st = AASM::Core::Transition.new(event, opts) expect(st.allowed?(nil)).to be_truthy end it 'should call the method on the object if guard is a symbol' do opts = {:from => 'foo', :to => 'bar', :guard => :test} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) expect(st.allowed?(obj)).to be false end it 'should add the name of the failed method calls to the failures instance var' do opts = {:from => 'foo', :to => 'bar', :guard => :test} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) st.allowed?(obj) expect(st.failures).to eq [:test] end it 'should call the method on the object if unless is a symbol' do opts = {:from => 'foo', :to => 'bar', :unless => :test} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) expect(st.allowed?(obj)).to be true end it 'should call the method on the object if guard is a string' do opts = {:from => 'foo', :to => 'bar', :guard => 'test'} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) expect(st.allowed?(obj)).to be false end it 'should call the method on the object if unless is a string' do opts = {:from => 'foo', :to => 'bar', :unless => 'test'} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) expect(st.allowed?(obj)).to be true end it 'should call the proc passing the object if the guard is a proc' do opts = {:from => 'foo', :to => 'bar', :guard => Proc.new { test }} st = AASM::Core::Transition.new(event, opts) obj = double('object') expect(obj).to receive(:test) expect(st.allowed?(obj)).to be false end end describe AASM::Core::Transition, '- when executing the transition with a Proc' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } it 'should call a Proc on the object with args' do opts = {:from => 'foo', :to => 'bar', :after => Proc.new {|a| test(a) }} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test).with(args) st.execute(obj, args) end it 'should call a Proc on the object without args' do # in order to test that the Proc has been called, we make sure # that after running the :after callback the prc_object is set prc_object = nil prc = Proc.new { prc_object = self } opts = {:from => 'foo', :to => 'bar', :after => prc } st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') st.execute(obj, args) expect(prc_object).to eql obj end end describe AASM::Core::Transition, '- when executing the transition with an :after method call' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } it 'should accept a String for the method name' do opts = {:from => 'foo', :to => 'bar', :after => 'test'} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test) st.execute(obj, args) end it 'should accept a Symbol for the method name' do opts = {:from => 'foo', :to => 'bar', :after => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test) st.execute(obj, args) end it 'should pass args if the target method accepts them' do opts = {:from => 'foo', :to => 'bar', :after => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') def obj.test(args) "arg1: #{args[:arg1]} arg2: #{args[:arg2]}" end return_value = st.execute(obj, args) expect(return_value).to eq('arg1: 1 arg2: 2') end it 'should NOT pass args if the target method does NOT accept them' do opts = {:from => 'foo', :to => 'bar', :after => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') def obj.test 'success' end return_value = st.execute(obj, args) expect(return_value).to eq('success') end it 'should allow accessing the from_state and the to_state' do opts = {:from => 'foo', :to => 'bar', :after => :test} transition = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => AASM::InstanceBase.new('object')) def obj.test(args) "from: #{aasm.from_state} to: #{aasm.to_state}" end return_value = transition.execute(obj, args) expect(return_value).to eq('from: foo to: bar') end end describe AASM::Core::Transition, '- when executing the transition with a Class' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } class AfterTransitionClass def initialize(record) @record = record end def call "from: #{@record.aasm.from_state} to: #{@record.aasm.to_state}" end end class AfterTransitionClassWithArgs def initialize(record, args) @record = record @args = args end def call "arg1: #{@args[:arg1]}, arg2: #{@args[:arg2]}" end end class AfterTransitionClassWithoutArgs def call 'success' end end it 'passes the record to the initialize method on the class to give access to the from_state and to_state' do opts = {:from => 'foo', :to => 'bar', :after => AfterTransitionClass} transition = AASM::Core::Transition.new(event, opts) obj = double('object', :aasm => AASM::InstanceBase.new('object')) return_value = transition.execute(obj) expect(return_value).to eq('from: foo to: bar') end it 'should pass args to the initialize method on the class if it accepts them' do opts = {:from => 'foo', :to => 'bar', :after => AfterTransitionClassWithArgs} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') return_value = st.execute(obj, args) expect(return_value).to eq('arg1: 1, arg2: 2') end it 'should NOT pass args if the call method of the class if it does NOT accept them' do opts = {:from => 'foo', :to => 'bar', :after => AfterTransitionClassWithoutArgs} st = AASM::Core::Transition.new(event, opts) obj = double('object', :aasm => 'aasm') return_value = st.execute(obj) expect(return_value).to eq('success') end end describe AASM::Core::Transition, '- when invoking the transition :success method call' do let(:state_machine) { AASM::StateMachine.new(:name) } let(:event) { AASM::Core::Event.new(:event, state_machine) } it 'should accept a String for the method name' do opts = {:from => 'foo', :to => 'bar', :success => 'test'} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test) st.invoke_success_callbacks(obj, args) end it 'should accept a Symbol for the method name' do opts = {:from => 'foo', :to => 'bar', :success => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test) st.invoke_success_callbacks(obj, args) end it 'should accept a Array for the method name' do opts = {:from => 'foo', :to => 'bar', :success => [:test1, :test2]} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') expect(obj).to receive(:test1) expect(obj).to receive(:test2) st.invoke_success_callbacks(obj, args) end it 'should pass args if the target method accepts them' do opts = {:from => 'foo', :to => 'bar', :success => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') def obj.test(args) "arg1: #{args[:arg1]} arg2: #{args[:arg2]}" end return_value = st.invoke_success_callbacks(obj, args) expect(return_value).to eq('arg1: 1 arg2: 2') end it 'should NOT pass args if the target method does NOT accept them' do opts = {:from => 'foo', :to => 'bar', :success => :test} st = AASM::Core::Transition.new(event, opts) args = {:arg1 => '1', :arg2 => '2'} obj = double('object', :aasm => 'aasm') def obj.test 'success' end return_value = st.invoke_success_callbacks(obj, args) expect(return_value).to eq('success') end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/timestamps_spec.rb
spec/unit/timestamps_spec.rb
require 'spec_helper' describe 'timestamps option' do it 'calls a timestamp setter based on the state name when entering a new state' do object = TimestampsExample.new expect { object.open }.to change { object.opened_at }.from(nil).to(instance_of(::Time)) end it 'overwrites any previous timestamp if a state is entered repeatedly' do object = TimestampsExample.new object.opened_at = ::Time.new(2000, 1, 1) expect { object.open }.to change { object.opened_at } end it 'does nothing if there is no setter matching the new state' do object = TimestampsExample.new expect { object.close }.not_to change { object.closed_at } end it 'can be turned off and on' do object = TimestampsExample.new object.class.aasm.state_machine.config.timestamps = false expect { object.open }.not_to change { object.opened_at } object.class.aasm.state_machine.config.timestamps = true expect { object.open }.to change { object.opened_at } end it 'calls a timestamp setter when using a named state machine' do object = TimestampsWithNamedMachineExample.new expect { object.open }.to change { object.opened_at }.from(nil).to(instance_of(::Time)) end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/dynamoid_persistence_multiple_spec.rb
spec/unit/persistence/dynamoid_persistence_multiple_spec.rb
require 'spec_helper' if defined?(Dynamoid) describe 'dynamoid' do Dir[File.dirname(__FILE__) + "/../../models/dynamoid/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = DynamoidMultiple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm(:left).current_state).to eq(:alpha) end it "should save the initial state" do model.save expect(model.status).to eq("alpha") end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm(:left).current_state).to eq(:beta) end it "should return the aasm column when not new and the aasm_column is not nil" do model.save model.status = "gamma" expect(model.aasm(:left).current_state).to eq(:gamma) end it "should allow a nil state" do model.save model.status = nil expect(model.aasm(:left).current_state).to be_nil end it "should not change the state if state is not loaded" do model.release model.save model.reload expect(model.aasm(:left).current_state).to eq(:beta) end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm(:left).states).to eq(@model.aasm(:left).states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm(:left).events).to eq(@model.aasm(:left).events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm(:left).attribute_name).to eq(:status) expect(Class.new(@model).aasm(:left).attribute_name).to eq(:status) end end describe 'initial states' do it 'should support conditions' do @model.aasm(:left) do initial_state lambda{ |m| m.default } end expect(@model.new(:default => :beta).aasm(:left).current_state).to eq(:beta) expect(@model.new(:default => :gamma).aasm(:left).current_state).to eq(:gamma) end end describe "complex example" do it "works" do record = ComplexDynamoidExample.new expect(record.aasm(:left).current_state).to eql :one expect(record.aasm(:right).current_state).to eql :alpha record.save expect_aasm_states record, :one, :alpha record.reload expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.reload expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.reload expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reset! expect_aasm_states record, :one, :beta end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right).to eql right_state.to_s end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/mongoid_persistence_multiple_spec.rb
spec/unit/persistence/mongoid_persistence_multiple_spec.rb
require 'spec_helper' if defined?(Mongoid::Document) describe 'mongoid' do Dir[File.dirname(__FILE__) + "/../../models/mongoid/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do # if you want to see the statements while running the spec enable the following line # Mongoid.logger = Logger.new(STDERR) end after do Mongoid.purge! end describe "named scopes with the old DSL" do context "Does not already respond_to? the scope name" do it "should add a scope for each state" do expect(SimpleMongoidMultiple).to respond_to(:unknown_scope) expect(SimpleMongoidMultiple).to respond_to(:another_unknown_scope) expect(SimpleMongoidMultiple.unknown_scope.class).to eq(Mongoid::Criteria) expect(SimpleMongoidMultiple.another_unknown_scope.class).to eq(Mongoid::Criteria) end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(SimpleMongoidMultiple).to respond_to(:new) expect(SimpleMongoidMultiple.new.class).to eq(SimpleMongoidMultiple) end end end describe "named scopes with the new DSL" do context "Does not already respond_to? the scope name" do it "should add a scope" do expect(SimpleNewDslMongoidMultiple).to respond_to(:unknown_scope) expect(SimpleNewDslMongoidMultiple.unknown_scope.class).to eq(Mongoid::Criteria) end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(SimpleNewDslMongoidMultiple).to respond_to(:new) expect(SimpleNewDslMongoidMultiple.new.class).to eq(SimpleNewDslMongoidMultiple) end end it "does not create scopes if requested" do expect(NoScopeMongoidMultiple).not_to respond_to(:ignored_scope) end end describe "instance methods" do let(:simple) {SimpleNewDslMongoidMultiple.new} it "should initialize the aasm state on instantiation" do expect(SimpleNewDslMongoidMultiple.new.status).to eql 'unknown_scope' expect(SimpleNewDslMongoidMultiple.new.aasm(:left).current_state).to eql :unknown_scope end end describe 'transitions with persistence' do it "should work for valid models" do valid_object = MultipleValidatorMongoid.create(:name => 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = MultipleValidatorMongoid.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(Mongoid::Errors::Validations) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = MultipleSilentPersistorMongoid.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = MultipleInvalidPersistorMongoid.create(:name => 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = MultipleInvalidPersistorMongoid.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end end describe "complex example" do it "works" do record = ComplexMongoidExample.new expect_aasm_states record, :one, :alpha record.save! expect_aasm_states record, :one, :alpha record.reload expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.reload expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.reload expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reset! expect_aasm_states record, :one, :beta end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right).to eql right_state.to_s end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/sequel_persistence_multiple_spec.rb
spec/unit/persistence/sequel_persistence_multiple_spec.rb
require 'spec_helper' if defined?(Sequel) describe 'sequel' do Dir[File.dirname(__FILE__) + "/../../models/sequel/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = Sequel::Multiple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm(:left).current_state).to eq(:alpha) end it "should save the initial state" do model.save expect(model.status).to eq("alpha") end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm(:left).current_state).to eq(:beta) end it "should return the aasm column when not new and the aasm_column is not nil" do allow(model).to receive(:new?).and_return(false) model.status = "gamma" expect(model.aasm(:left).current_state).to eq(:gamma) end it "should allow a nil state" do allow(model).to receive(:new?).and_return(false) model.status = nil expect(model.aasm(:left).current_state).to be_nil end it "should not change the state if state is not loaded" do model.release model.save model.class.select(:id).first.save model.reload expect(model.aasm(:left).current_state).to eq(:beta) end it "should call aasm_ensure_initial_state on validation before create" do expect(model).to receive(:aasm_ensure_initial_state).and_return(true) model.valid? end it "should call aasm_ensure_initial_state before create, even if skipping validations" do expect(model).to receive(:aasm_ensure_initial_state).and_return(true) model.save(:validate => false) end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm(:left).states).to eq(@model.aasm(:left).states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm(:left).events).to eq(@model.aasm(:left).events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm(:left).attribute_name).to eq(:status) expect(Class.new(@model).aasm(:left).attribute_name).to eq(:status) end end describe 'initial states' do it 'should support conditions' do @model.aasm(:left) do initial_state lambda{ |m| m.default } end expect(@model.new(:default => :beta).aasm(:left).current_state).to eq(:beta) expect(@model.new(:default => :gamma).aasm(:left).current_state).to eq(:gamma) end end describe "complex example" do it "works" do record = Sequel::ComplexExample.new expect(record.aasm(:left).current_state).to eql :one expect(record.left).to be_nil expect(record.aasm(:right).current_state).to eql :alpha expect(record.right).to be_nil record.save expect_aasm_states record, :one, :alpha record.reload expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.reload expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.reload expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reset! expect_aasm_states record, :one, :beta end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right).to eql right_state.to_s end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/redis_persistence_multiple_spec.rb
spec/unit/persistence/redis_persistence_multiple_spec.rb
require 'spec_helper' if defined?(Redis) describe 'redis' do Dir[File.dirname(__FILE__) + "/../../models/redis/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = RedisMultiple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm(:left).current_state).to eq(:alpha) end it "should save the initial state" do expect(model.status).to eq("alpha") end it "should return the aasm column the aasm field is not nil" do model.status = "beta" expect(model.aasm(:left).current_state).to eq(:beta) end it "should allow a nil state" do model.status = nil expect(model.aasm(:left).current_state).to be_nil end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm(:left).states).to eq(@model.aasm(:left).states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm(:left).events).to eq(@model.aasm(:left).events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm(:left).attribute_name).to eq(:status) expect(Class.new(@model).aasm(:left).attribute_name).to eq(:status) end end describe "complex example" do it "works" do record = RedisComplexExample.new expect(record.aasm(:left).current_state).to eql :one expect(record.aasm(:right).current_state).to eql :alpha expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left.value.to_s).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right.value.to_s).to eql right_state.to_s end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/no_brainer_persistence_multiple_spec.rb
spec/unit/persistence/no_brainer_persistence_multiple_spec.rb
require 'spec_helper' if defined?(NoBrainer::Document) describe 'nobrainer' do Dir[File.dirname(__FILE__) + '/../../models/nobrainer/*.rb'].sort.each do |f| require File.expand_path(f) end before(:all) do # if you want to see the statements while running the spec enable the # following line # NoBrainer.configure do |config| # config.logger = Logger.new(STDERR) # end end after do NoBrainer.purge! end describe 'named scopes with the old DSL' do context 'Does not already respond_to? the scope name' do it 'should add a scope for each state' do expect(SimpleNoBrainerMultiple).to respond_to(:unknown_scope) expect(SimpleNoBrainerMultiple).to respond_to(:another_unknown_scope) expect(SimpleNoBrainerMultiple.unknown_scope.class).to eq(NoBrainer::Criteria) expect(SimpleNoBrainerMultiple.another_unknown_scope.class).to eq(NoBrainer::Criteria) end end context 'Already respond_to? the scope name' do it 'should not add a scope' do expect(SimpleNoBrainerMultiple).to respond_to(:new) expect(SimpleNoBrainerMultiple.new.class).to eq(SimpleNoBrainerMultiple) end end end describe 'named scopes with the new DSL' do context 'Does not already respond_to? the scope name' do it 'should add a scope' do expect(SimpleNewDslNoBrainerMultiple).to respond_to(:unknown_scope) expect(SimpleNewDslNoBrainerMultiple.unknown_scope.class).to eq(NoBrainer::Criteria) end end context 'Already respond_to? the scope name' do it 'should not add a scope' do expect(SimpleNewDslNoBrainerMultiple).to respond_to(:new) expect(SimpleNewDslNoBrainerMultiple.new.class).to eq(SimpleNewDslNoBrainerMultiple) end end it 'does not create scopes if requested' do expect(NoScopeNoBrainerMultiple).not_to respond_to(:ignored_scope) end end describe 'instance methods' do let(:simple) { SimpleNewDslNoBrainerMultiple.new } it 'should initialize the aasm state on instantiation' do expect(SimpleNewDslNoBrainerMultiple.new.status).to eql 'unknown_scope' expect(SimpleNewDslNoBrainerMultiple.new.aasm(:left).current_state).to eql :unknown_scope end end describe 'transitions with persistence' do it 'should work for valid models' do valid_object = MultipleValidatorNoBrainer.create(name: 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = MultipleValidatorNoBrainer.create(name: 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(NoBrainer::Error::DocumentInvalid) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = MultipleSilentPersistorNoBrainer.create(name: 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = MultipleInvalidPersistorNoBrainer.create(name: 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = MultipleInvalidPersistorNoBrainer.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end end describe 'complex example' do it 'works' do record = ComplexNoBrainerExample.new expect_aasm_states record, :one, :alpha record.save! expect_aasm_states record, :one, :alpha record.reload expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.reload expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.reload expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reset! expect_aasm_states record, :one, :beta end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right).to eql right_state.to_s end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/sequel_persistence_spec.rb
spec/unit/persistence/sequel_persistence_spec.rb
require 'spec_helper' if defined?(Sequel) describe 'sequel' do Dir[File.dirname(__FILE__) + "/../../models/sequel/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = Sequel::Simple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm.current_state).to eq(:alpha) end it "should save the initial state" do model.save expect(model.status).to eq("alpha") end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm.current_state).to eq(:beta) end it "should return the aasm column when not new and the aasm_column is not nil" do allow(model).to receive(:new?).and_return(false) model.status = "gamma" expect(model.aasm.current_state).to eq(:gamma) end it "should allow a nil state" do allow(model).to receive(:new?).and_return(false) model.status = nil expect(model.aasm.current_state).to be_nil end it "should not change the state if state is not loaded" do model.release model.save model.class.select(:id).first.save model.reload expect(model.aasm.current_state).to eq(:beta) end it "should call aasm_ensure_initial_state on validation before create" do expect(model).to receive(:aasm_ensure_initial_state).and_return(true) model.valid? end it "should call aasm_ensure_initial_state before create, even if skipping validations" do expect(model).to receive(:aasm_ensure_initial_state).and_return(true) model.save(:validate => false) end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm.states).to eq(@model.aasm.states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm.events).to eq(@model.aasm.events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm.attribute_name).to eq(:status) expect(Class.new(@model).aasm.attribute_name).to eq(:status) end end describe 'initial states' do it 'should support conditions' do @model.aasm do initial_state lambda{ |m| m.default } end expect(@model.new(:default => :beta).aasm.current_state).to eq(:beta) expect(@model.new(:default => :gamma).aasm.current_state).to eq(:gamma) end end describe 'transitions with persistence' do it "should work for valid models" do valid_object = Sequel::Validator.create(:name => 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(Sequel::ValidationFailed) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = Sequel::SilentPersistor.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = Sequel::InvalidPersistor.create(:name => 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = Sequel::InvalidPersistor[persistor.id] persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end describe 'pessimistic locking' do let(:worker) { Sequel::Worker.create(:name => 'worker', :status => 'sleeping') } subject { transactor.run! } context 'no lock' do let(:transactor) { Sequel::NoLockTransactor.create(:name => 'no_lock_transactor', :worker => worker) } it 'should not invoke lock!' do expect(transactor).to_not receive(:lock!) subject end end context 'a default lock' do let(:transactor) { Sequel::LockTransactor.create(:name => 'lock_transactor', :worker => worker) } it 'should invoke lock!' do expect(transactor).to receive(:lock!).and_call_original subject end end context 'a FOR UPDATE NOWAIT lock' do let(:transactor) { Sequel::LockNoWaitTransactor.create(:name => 'lock_no_wait_transactor', :worker => worker) } it 'should invoke lock! with FOR UPDATE NOWAIT' do # TODO: With and_call_original, get an error with syntax, should look into it. expect(transactor).to receive(:lock!).with('FOR UPDATE NOWAIT')# .and_call_original subject end end end describe 'transactions' do let(:worker) { Sequel::Worker.create(:name => 'worker', :status => 'sleeping') } let(:transactor) { Sequel::Transactor.create(:name => 'transactor', :worker => worker) } it 'should rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') expect {transactor.run!}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end context "nested transactions" do it "should rollback all changes in nested transaction" do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Sequel::Worker.db.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end it "should only rollback changes in the main transaction not the nested one" do # change configuration to not require new transaction AASM::StateMachineStore[Sequel::Transactor][:default].config.requires_new_transaction = false expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Sequel::Worker.db.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('running') end end describe "after_commit callback" do it "should fire :after_commit if transaction was successful" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping validator.run! expect(validator).to be_running expect(validator.name).to eq("name changed") validator.sleep!("sleeper") expect(validator).to be_sleeping expect(validator.name).to eq("sleeper") end it "should not fire :after_commit if transaction failed" do validator = Sequel::Validator.create(:name => 'name') expect { validator.fail! }.to raise_error(StandardError, 'failed on purpose') expect(validator.name).to eq("name") end it "should not fire :after_commit if validation failed when saving object" do validator = Sequel::Validator.create(:name => 'name') validator.invalid = true expect { validator.run! }.to raise_error(Sequel::ValidationFailed, 'validator invalid') expect(validator).to be_sleeping expect(validator.name).to eq("name") end it "should not fire if not saving" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping validator.run expect(validator).to be_running expect(validator.name).to eq("name") end end describe 'before and after transaction callbacks' do [:after, :before].each do |event_type| describe "#{event_type}_transaction callback" do it "should fire :#{event_type}_transaction if transaction was successful" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run! }.to change { validator.send("#{event_type}_transaction_performed_on_run") }.from(nil).to(true) expect(validator).to be_running end it "should fire :#{event_type}_transaction if transaction failed" do validator = Sequel::Validator.create(:name => 'name') expect do begin validator.fail! rescue => ignored end end.to change { validator.send("#{event_type}_transaction_performed_on_fail") }.from(nil).to(true) expect(validator).to_not be_running end it "should not fire :#{event_type}_transaction if not saving" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run }.to_not change { validator.send("#{event_type}_transaction_performed_on_run") } expect(validator).to be_running expect(validator.name).to eq("name") end end end end describe 'before and after all transactions callbacks' do [:after, :before].each do |event_type| describe "#{event_type}_all_transactions callback" do it "should fire :#{event_type}_all_transactions if transaction was successful" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run! }.to change { validator.send("#{event_type}_all_transactions_performed") }.from(nil).to(true) expect(validator).to be_running end it "should fire :#{event_type}_all_transactions if transaction failed" do validator = Sequel::Validator.create(:name => 'name') expect do begin validator.fail! rescue => ignored end end.to change { validator.send("#{event_type}_all_transactions_performed") }.from(nil).to(true) expect(validator).to_not be_running end it "should not fire :#{event_type}_all_transactions if not saving" do validator = Sequel::Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run }.to_not change { validator.send("#{event_type}_all_transactions_performed") } expect(validator).to be_running expect(validator.name).to eq("name") end end end end context "when not persisting" do it 'should not rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') # Notice here we're calling "run" and not "run!" with a bang. expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('running') end it 'should not create a database transaction' do expect(transactor.class).not_to receive(:transaction) expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') end end end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/active_record_persistence_multiple_spec.rb
spec/unit/persistence/active_record_persistence_multiple_spec.rb
require 'spec_helper' if defined?(ActiveRecord) Dir[File.dirname(__FILE__) + "/../../models/active_record/*.rb"].sort.each do |f| require File.expand_path(f) end load_schema # if you want to see the statements while running the spec enable the following line # require 'logger' # ActiveRecord::Base.logger = Logger.new(STDERR) describe "instance methods" do let(:gate) {MultipleGate.new} it "should respond to aasm persistence methods" do expect(gate).to respond_to(:aasm_read_state) expect(gate).to respond_to(:aasm_write_state) expect(gate).to respond_to(:aasm_write_state_without_persistence) end describe "aasm_column_looks_like_enum" do subject { lambda{ gate.send(:aasm_column_looks_like_enum, :left) } } let(:column_name) { "value" } let(:columns_hash) { Hash[column_name, column] } before :each do allow(gate.class.aasm(:left)).to receive(:attribute_name).and_return(column_name.to_sym) allow(gate.class).to receive(:columns_hash).and_return(columns_hash) end context "when AASM column has integer type" do let(:column) { double(Object, type: :integer) } it "returns true" do expect(subject.call).to be_truthy end end context "when AASM column has string type" do let(:column) { double(Object, type: :string) } it "returns false" do expect(subject.call).to be_falsey end end end describe "aasm_guess_enum_method" do subject { lambda{ gate.send(:aasm_guess_enum_method, :left) } } before :each do allow(gate.class.aasm(:left)).to receive(:attribute_name).and_return(:value) end it "pluralizes AASM column name" do expect(subject.call).to eq :values end end describe "aasm_enum" do context "when AASM enum setting contains an explicit enum method name" do let(:with_enum) { MultipleWithEnum.new } it "returns whatever value was set in AASM config" do expect(with_enum.send(:aasm_enum, :left)).to eq :test end end context "when AASM enum setting is simply set to true" do let(:with_true_enum) { MultipleWithTrueEnum.new } before :each do allow(MultipleWithTrueEnum.aasm(:left)).to receive(:attribute_name).and_return(:value) end it "infers enum method name from pluralized column name" do expect(with_true_enum.send(:aasm_enum, :left)).to eq :values end end context "when AASM enum setting is explicitly disabled" do let(:with_false_enum) { MultipleWithFalseEnum.new } it "returns nil" do expect(with_false_enum.send(:aasm_enum, :left)).to be_nil end end context "when AASM enum setting is not enabled" do before :each do allow(MultipleGate.aasm(:left)).to receive(:attribute_name).and_return(:value) end context "when AASM column looks like enum" do before :each do allow(gate).to receive(:aasm_column_looks_like_enum).with(:left).and_return(true) end it "infers enum method name from pluralized column name" do expect(gate.send(:aasm_enum, :left)).to eq :values end end context "when AASM column doesn't look like enum'" do before :each do allow(gate).to receive(:aasm_column_looks_like_enum) .and_return(false) end it "returns nil, as we're not using enum" do expect(gate.send(:aasm_enum, :left)).to be_nil end end end if ActiveRecord::VERSION::MAJOR >= 4 && ActiveRecord::VERSION::MINOR >= 1 # won't work with Rails <= 4.1 # Enum are introduced from Rails 4.1, therefore enum syntax will not work on Rails <= 4.1 context "when AASM enum setting is not enabled and aasm column not present" do let(:multiple_with_enum_without_column) {MultipleWithEnumWithoutColumn.new} it "should raise an error for transitions" do if ActiveRecord.gem_version >= Gem::Version.new('7.1.0') expect{multiple_with_enum_without_column.send(:view, :left)}.to raise_error(RuntimeError, /Undeclared attribute type for enum 'status'/) else expect{multiple_with_enum_without_column.send(:view, :left)}.to raise_error(NoMethodError, /undefined method .status./) end end end end end context "when AASM is configured to use enum" do let(:state_sym) { :running } let(:state_code) { 2 } let(:enum_name) { :states } let(:enum) { Hash[state_sym, state_code] } before :each do allow(gate).to receive(:aasm_enum).and_return(enum_name) allow(gate).to receive(:aasm_write_state_attribute) allow(gate).to receive(:write_attribute) allow(MultipleGate).to receive(enum_name).and_return(enum) end describe "aasm_write_state" do context "when AASM is configured to skip validations on save" do before :each do allow(gate).to receive(:aasm_skipping_validations).and_return(true) end it "passes state code instead of state symbol to update_all" do # stub_chain does not allow us to give expectations on call # parameters in the middle of the chain, so we need to use # intermediate object instead. obj = double(Object, update_all: 1) allow(MultipleGate).to receive_message_chain(:unscoped, :where) .and_return(obj) gate.aasm_write_state state_sym, :left expect(obj).to have_received(:update_all) .with(Hash[gate.class.aasm(:left).attribute_name, state_code]) end end context "when AASM is not skipping validations" do it "delegates state update to the helper method" do # Let's pretend that validation is passed allow(gate).to receive(:save).and_return(true) gate.aasm_write_state state_sym, :left expect(gate).to have_received(:aasm_write_state_attribute).with(state_sym, :left) expect(gate).to_not have_received :write_attribute end end end describe "aasm_write_state_without_persistence" do it "delegates state update to the helper method" do gate.aasm_write_state_without_persistence state_sym, :left expect(gate).to have_received(:aasm_write_state_attribute).with(state_sym, :left) expect(gate).to_not have_received :write_attribute end end describe "aasm_raw_attribute_value" do it "converts state symbol to state code" do expect(gate.send(:aasm_raw_attribute_value, state_sym)) .to eq state_code end end end context "when AASM is configured to use string field" do let(:state_sym) { :running } before :each do allow(gate).to receive(:aasm_enum).and_return(nil) end describe "aasm_raw_attribute_value" do it "converts state symbol to string" do expect(gate.send(:aasm_raw_attribute_value, state_sym)) .to eq state_sym.to_s end end end describe "aasm_write_attribute helper method" do let(:sym) { :sym } let(:value) { 42 } before :each do allow(gate).to receive(:write_attribute) allow(gate).to receive(:aasm_raw_attribute_value).and_return(value) gate.send(:aasm_write_state_attribute, sym, :left) end it "generates attribute value using a helper method" do expect(gate).to have_received(:aasm_raw_attribute_value).with(sym, :left) end it "writes attribute to the model" do expect(gate).to have_received(:write_attribute).with(:aasm_state, value) end end it "should return the initial state when new and the aasm field is nil" do expect(gate.aasm(:left).current_state).to eq(:opened) end it "should return the aasm column when new and the aasm field is not nil" do gate.aasm_state = "closed" expect(gate.aasm(:left).current_state).to eq(:closed) end it "should return the aasm column when not new and the aasm.attribute_name is not nil" do allow(gate).to receive(:new_record?).and_return(false) gate.aasm_state = "state" expect(gate.aasm(:left).current_state).to eq(:state) end it "should allow a nil state" do allow(gate).to receive(:new_record?).and_return(false) gate.aasm_state = nil expect(gate.aasm(:left).current_state).to be_nil end context 'on initialization' do it "should initialize the aasm state" do expect(MultipleGate.new.aasm_state).to eql 'opened' expect(MultipleGate.new.aasm(:left).current_state).to eql :opened end it "should not initialize the aasm state if it has not been loaded" do # we have to create a gate in the database, for which we only want to # load the id, and not the state gate = MultipleGate.create! # then we just load the gate ids MultipleGate.select(:id).where(id: gate.id).first end end end if ActiveRecord::VERSION::MAJOR < 4 && ActiveRecord::VERSION::MINOR < 2 # won't work with Rails >= 4.2 describe "direct state column access" do it "accepts false states" do f = MultipleFalseState.create! expect(f.aasm_state).to eql false expect { f.aasm(:left).events.map(&:name) }.to_not raise_error end end end describe 'subclasses' do it "should have the same states as its parent class" do expect(MultipleDerivateNewDsl.aasm(:left).states).to eq(MultipleSimpleNewDsl.aasm(:left).states) end it "should have the same events as its parent class" do expect(MultipleDerivateNewDsl.aasm(:left).events).to eq(MultipleSimpleNewDsl.aasm(:left).events) end it "should have the same column as its parent even for the new dsl" do expect(MultipleSimpleNewDsl.aasm(:left).attribute_name).to eq(:status) expect(MultipleDerivateNewDsl.aasm(:left).attribute_name).to eq(:status) end end describe "named scopes with the new DSL" do context "Does not already respond_to? the scope name" do it "should add a scope for each state" do expect(MultipleSimpleNewDsl).to respond_to(:unknown_scope) expect(MultipleSimpleNewDsl).to respond_to(:another_unknown_scope) expect(MultipleSimpleNewDsl.unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy expect(MultipleSimpleNewDsl.another_unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(MultipleSimpleNewDsl).to respond_to(:new) expect(MultipleSimpleNewDsl.new.class).to eq(MultipleSimpleNewDsl) end end it "does not create scopes if requested" do expect(MultipleNoScope).not_to respond_to(:pending) end context "result of scope" do let!(:dsl1) { MultipleSimpleNewDsl.create!(status: :new) } let!(:dsl2) { MultipleSimpleNewDsl.create!(status: :unknown_scope) } after do MultipleSimpleNewDsl.destroy_all end it "created scope works as where(name: :scope_name)" do expect(MultipleSimpleNewDsl.unknown_scope).to contain_exactly(dsl2) end end context "when namespeced" do it "add namespaced scopes" do expect(MultipleNamespaced).to respond_to(:car_unsold) expect(MultipleNamespaced).to respond_to(:car_sold) expect(MultipleNamespaced.car_unsold.is_a?(ActiveRecord::Relation)).to be_truthy expect(MultipleNamespaced.car_sold.is_a?(ActiveRecord::Relation)).to be_truthy end it "add unnamespaced scopes" do expect(MultipleNamespaced).to respond_to(:unsold) expect(MultipleNamespaced).to respond_to(:sold) expect(MultipleNamespaced.unsold.is_a?(ActiveRecord::Relation)).to be_truthy expect(MultipleNamespaced.sold.is_a?(ActiveRecord::Relation)).to be_truthy end end end # scopes describe "direct assignment" do it "is allowed by default" do obj = MultipleNoScope.create expect(obj.aasm_state.to_sym).to eql :pending obj.aasm_state = :running expect(obj.aasm_state.to_sym).to eql :running end it "is forbidden if configured" do obj = MultipleNoDirectAssignment.create expect(obj.aasm_state.to_sym).to eql :pending expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :pending end it 'can be turned off and on again' do obj = MultipleNoDirectAssignment.create expect(obj.aasm_state.to_sym).to eql :pending expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :pending # allow it temporarily MultipleNoDirectAssignment.aasm(:left).state_machine.config.no_direct_assignment = false obj.aasm_state = :running expect(obj.aasm_state.to_sym).to eql :running # and forbid it again MultipleNoDirectAssignment.aasm(:left).state_machine.config.no_direct_assignment = true expect {obj.aasm_state = :pending}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :running end end # direct assignment describe 'initial states' do it 'should support conditions' do expect(MultipleThief.new(:skilled => true).aasm(:left).current_state).to eq(:rich) expect(MultipleThief.new(:skilled => false).aasm(:left).current_state).to eq(:jailed) end end describe 'transitions with persistence' do it "should work for valid models" do valid_object = MultipleValidator.create(:name => 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = MultipleValidator.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(ActiveRecord::RecordInvalid) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = MultipleSilentPersistor.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = MultipleInvalidPersistor.create(:name => 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = MultipleInvalidPersistor.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end describe 'transactions' do let(:worker) { Worker.create!(:name => 'worker', :status => 'sleeping') } let(:transactor) { MultipleTransactor.create!(:name => 'transactor', :worker => worker) } it 'should rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') expect {transactor.run!}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end context "nested transactions" do it "should rollback all changes in nested transaction" do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Worker.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end it "should only rollback changes in the main transaction not the nested one" do # change configuration to not require new transaction AASM::StateMachineStore[MultipleTransactor][:left].config.requires_new_transaction = false expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Worker.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('running') end end describe "after_commit callback" do it "should fire :after_commit if transaction was successful" do validator = MultipleValidator.create(:name => 'name') expect(validator).to be_sleeping validator.run! expect(validator).to be_running expect(validator.name).to eq("name changed") validator.sleep!("sleeper") expect(validator).to be_sleeping expect(validator.name).to eq("sleeper") end it "should not fire :after_commit if transaction failed" do validator = MultipleValidator.create(:name => 'name') expect { validator.fail! }.to raise_error(StandardError, 'failed on purpose') expect(validator.name).to eq("name") end it "should not fire if not saving" do validator = MultipleValidator.create(:name => 'name') expect(validator).to be_sleeping validator.run expect(validator).to be_running expect(validator.name).to eq("name") end end context "when not persisting" do it 'should not rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') # Notice here we're calling "run" and not "run!" with a bang. expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('running') end it 'should not create a database transaction' do expect(transactor.class).not_to receive(:transaction) expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') end end end end describe "invalid states with persistence" do it "should not store states" do validator = MultipleValidator.create(:name => 'name') validator.status = 'invalid_state' expect(validator.save).to be_falsey expect {validator.save!}.to raise_error(ActiveRecord::RecordInvalid) validator.reload expect(validator).to be_sleeping end it "should store invalid states if configured" do persistor = MultipleInvalidPersistor.create(:name => 'name') persistor.status = 'invalid_state' expect(persistor.save).to be_truthy persistor.reload expect(persistor.status).to eq('invalid_state') end end describe "complex example" do it "works" do record = ComplexActiveRecordExample.new expect_aasm_states record, :one, :alpha record.save! expect_aasm_states record, :one, :alpha record.reload expect_aasm_states record, :one, :alpha record.increment! expect_aasm_states record, :two, :alpha record.reload expect_aasm_states record, :two, :alpha record.level_up! expect_aasm_states record, :two, :beta record.reload expect_aasm_states record, :two, :beta record.increment! expect { record.increment! }.to raise_error(AASM::InvalidTransition) expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :beta record.level_up! expect_aasm_states record, :three, :gamma record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reload expect_aasm_states record, :three, :gamma record.level_down # without saving expect_aasm_states record, :three, :beta record.reset! expect_aasm_states record, :one, :beta end def expect_aasm_states(record, left_state, right_state) expect(record.aasm(:left).current_state).to eql left_state.to_sym expect(record.left).to eql left_state.to_s expect(record.aasm(:right).current_state).to eql right_state.to_sym expect(record.right).to eql right_state.to_s end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/mongoid_persistence_spec.rb
spec/unit/persistence/mongoid_persistence_spec.rb
require 'spec_helper' if defined?(Mongoid::Document) describe 'mongoid' do Dir[File.dirname(__FILE__) + "/../../models/mongoid/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do # if you want to see the statements while running the spec enable the following line # Mongoid.logger = Logger.new(STDERR) end after do Mongoid.purge! end describe "named scopes with the old DSL" do context "Does not already respond_to? the scope name" do it "should add a scope for each state" do expect(SimpleMongoid).to respond_to(:unknown_scope) expect(SimpleMongoid).to respond_to(:another_unknown_scope) expect(SimpleMongoid.unknown_scope.class).to eq(Mongoid::Criteria) expect(SimpleMongoid.another_unknown_scope.class).to eq(Mongoid::Criteria) end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(SimpleMongoid).to respond_to(:new) expect(SimpleMongoid.new.class).to eq(SimpleMongoid) end end end describe "named scopes with the new DSL" do context "Does not already respond_to? the scope name" do it "should add a scope" do expect(SimpleNewDslMongoid).to respond_to(:unknown_scope) expect(SimpleNewDslMongoid.unknown_scope.class).to eq(Mongoid::Criteria) end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(SimpleNewDslMongoid).to respond_to(:new) expect(SimpleNewDslMongoid.new.class).to eq(SimpleNewDslMongoid) end end it "does not create scopes if requested" do expect(NoScopeMongoid).not_to respond_to(:ignored_scope) end end describe "instance methods" do let(:simple) {SimpleNewDslMongoid.new} it "should initialize the aasm state on instantiation" do expect(SimpleNewDslMongoid.new.status).to eql 'unknown_scope' expect(SimpleNewDslMongoid.new.aasm.current_state).to eql :unknown_scope end end describe "relations object" do it "should load relations object ids" do parent = Parent.create child_1 = Child.create(parent_id: parent.id) child_2 = Child.create(parent_id: parent.id) expect(parent.child_ids).to eql [child_1.id, child_2.id] end end describe 'transitions with persistence' do it 'should work for valid models' do valid_object = ValidatorMongoid.create(:name => 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = ValidatorMongoid.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(Mongoid::Errors::Validations) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = SilentPersistorMongoid.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = InvalidPersistorMongoid.create(:name => 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = InvalidPersistorMongoid.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end end describe 'testing the timestamps option' do let(:example) { TimestampExampleMongoid.create } it 'should update existing timestamp fields' do expect { example.open! }.to change { example.reload.opened_at }.from(nil).to(instance_of(::Time)) end it 'should not fail if there is no corresponding timestamp field' do expect { example.close! }.to change { example.reload.status } end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/active_record_persistence_spec.rb
spec/unit/persistence/active_record_persistence_spec.rb
require 'spec_helper' if defined?(ActiveRecord) Dir[File.dirname(__FILE__) + "/../../models/active_record/*.rb"].sort.each do |f| require File.expand_path(f) end load_schema # if you want to see the statements while running the spec enable the following line # require 'logger' # ActiveRecord::Base.logger = Logger.new(STDERR) describe "instance methods" do let(:gate) {Gate.new} it "should respond to aasm persistence methods" do expect(gate).to respond_to(:aasm_read_state) expect(gate).to respond_to(:aasm_write_state) expect(gate).to respond_to(:aasm_write_state_without_persistence) end describe "aasm_column_looks_like_enum" do subject { lambda{ gate.send(:aasm_column_looks_like_enum) } } let(:column_name) { "value" } let(:columns_hash) { Hash[column_name, column] } before :each do allow(gate.class.aasm).to receive(:attribute_name).and_return(column_name.to_sym) allow(gate.class).to receive(:columns_hash).and_return(columns_hash) end context "when AASM column has integer type" do let(:column) { double(Object, type: :integer) } it "returns true" do expect(subject.call).to be_truthy end end context "when AASM column has string type" do let(:column) { double(Object, type: :string) } it "returns false" do expect(subject.call).to be_falsey end end end describe "aasm_guess_enum_method" do subject { lambda{ gate.send(:aasm_guess_enum_method) } } before :each do allow(gate.class.aasm).to receive(:attribute_name).and_return(:value) end it "pluralizes AASM column name" do expect(subject.call).to eq :values end end describe "aasm_enum" do context "when AASM enum setting contains an explicit enum method name" do let(:with_enum) { WithEnum.new } it "returns whatever value was set in AASM config" do expect(with_enum.send(:aasm_enum)).to eq :test end end context "when AASM enum setting is simply set to true" do let(:with_true_enum) { WithTrueEnum.new } before :each do allow(WithTrueEnum.aasm).to receive(:attribute_name).and_return(:value) end it "infers enum method name from pluralized column name" do expect(with_true_enum.send(:aasm_enum)).to eq :values end end context "when AASM enum setting is explicitly disabled" do let(:with_false_enum) { WithFalseEnum.new } it "returns nil" do expect(with_false_enum.send(:aasm_enum)).to be_nil end end context "when AASM enum setting is not enabled" do before :each do allow(Gate.aasm).to receive(:attribute_name).and_return(:value) end context "when AASM column looks like enum" do before :each do allow(gate).to receive(:aasm_column_looks_like_enum).and_return(true) end it "infers enum method name from pluralized column name" do expect(gate.send(:aasm_enum)).to eq :values end end context "when AASM column doesn't look like enum'" do before :each do allow(gate).to receive(:aasm_column_looks_like_enum) .and_return(false) end it "returns nil, as we're not using enum" do expect(gate.send(:aasm_enum)).to be_nil end end end if ActiveRecord::VERSION::MAJOR >= 4 && ActiveRecord::VERSION::MINOR >= 1 # won't work with Rails <= 4.1 # Enum are introduced from Rails 4.1, therefore enum syntax will not work on Rails <= 4.1 context "when AASM enum setting is not enabled and aasm column not present" do let(:with_enum_without_column) {WithEnumWithoutColumn.new} it "should raise an error for transitions" do if ActiveRecord.gem_version >= Gem::Version.new('7.1.0') expect{with_enum_without_column.send(:view)}.to raise_error(RuntimeError, /Undeclared attribute type for enum 'status'/) else expect{with_enum_without_column.send(:view)}.to raise_error(NoMethodError, /undefined method .status./) end end end end end context "when AASM is configured to use enum" do let(:state_sym) { :running } let(:state_code) { 2 } let(:enum_name) { :states } let(:enum) { Hash[state_sym, state_code] } before :each do allow(gate).to receive(:aasm_enum).and_return(enum_name) allow(gate).to receive(:aasm_write_state_attribute) allow(gate).to receive(:write_attribute) allow(Gate).to receive(enum_name).and_return(enum) end describe "aasm_write_state" do context "when AASM is configured to skip validations on save" do before :each do allow(gate).to receive(:aasm_skipping_validations).and_return(true) end it "passes state code instead of state symbol to update_all" do # stub_chain does not allow us to give expectations on call # parameters in the middle of the chain, so we need to use # intermediate object instead. obj = double(Object, update_all: 1) allow(Gate).to receive_message_chain(:unscoped, :where).and_return(obj) gate.aasm_write_state state_sym expect(obj).to have_received(:update_all) .with(Hash[gate.class.aasm.attribute_name, state_code]) end it "searches model outside of default_scope when update_all" do # stub_chain does not allow us to give expectations on call # parameters in the middle of the chain, so we need to use # intermediate object instead. unscoped = double(Object, update_all: 1) scoped = double(Object, update_all: 1) allow(Gate).to receive(:unscoped).and_return(unscoped) allow(Gate).to receive(:where).and_return(scoped) allow(unscoped).to receive(:where).and_return(unscoped) gate.aasm_write_state state_sym expect(unscoped).to have_received(:update_all) .with(Hash[gate.class.aasm.attribute_name, state_code]) expect(scoped).to_not have_received(:update_all) .with(Hash[gate.class.aasm.attribute_name, state_code]) end end context "when AASM is not skipping validations" do it "delegates state update to the helper method" do # Let's pretend that validation is passed allow(gate).to receive(:save).and_return(true) gate.aasm_write_state state_sym expect(gate).to have_received(:aasm_write_state_attribute).with(state_sym, :default) expect(gate).to_not have_received :write_attribute end end end describe "aasm_write_state_without_persistence" do it "delegates state update to the helper method" do gate.aasm_write_state_without_persistence state_sym expect(gate).to have_received(:aasm_write_state_attribute).with(state_sym, :default) expect(gate).to_not have_received :write_attribute end end describe "aasm_raw_attribute_value" do it "converts state symbol to state code" do expect(gate.send(:aasm_raw_attribute_value, state_sym)) .to eq state_code end end end context "when AASM is configured to use string field" do let(:state_sym) { :running } before :each do allow(gate).to receive(:aasm_enum).and_return(nil) end describe "aasm_raw_attribute_value" do it "converts state symbol to string" do expect(gate.send(:aasm_raw_attribute_value, state_sym)) .to eq state_sym.to_s end end end describe "aasm_write_attribute helper method" do let(:sym) { :sym } let(:value) { 42 } before :each do allow(gate).to receive(:write_attribute) allow(gate).to receive(:aasm_raw_attribute_value).and_return(value) gate.send(:aasm_write_state_attribute, sym) end it "generates attribute value using a helper method" do expect(gate).to have_received(:aasm_raw_attribute_value).with(sym, :default) end it "writes attribute to the model" do expect(gate).to have_received(:write_attribute).with(:aasm_state, value) end end it "should return the initial state when new and the aasm field is nil" do expect(gate.aasm.current_state).to eq(:opened) end it "should return the aasm column when new and the aasm field is not nil" do gate.aasm_state = "closed" expect(gate.aasm.current_state).to eq(:closed) end it "should return the aasm column when not new and the aasm.attribute_name is not nil" do allow(gate).to receive(:new_record?).and_return(false) gate.aasm_state = "state" expect(gate.aasm.current_state).to eq(:state) end it "should allow a nil state" do allow(gate).to receive(:new_record?).and_return(false) gate.aasm_state = nil expect(gate.aasm.current_state).to be_nil end context 'on initialization' do it "should initialize the aasm state" do expect(Gate.new.aasm_state).to eql 'opened' expect(Gate.new.aasm.current_state).to eql :opened end it "should not initialize the aasm state if it has not been loaded" do # we have to create a gate in the database, for which we only want to # load the id, and not the state gate = Gate.create! # then we just load the gate ids Gate.select(:id).where(id: gate.id).first end end end if ActiveRecord::VERSION::MAJOR < 4 && ActiveRecord::VERSION::MINOR < 2 # won't work with Rails >= 4.2 describe "direct state column access" do it "accepts false states" do f = FalseState.create! expect(f.aasm_state).to eql false expect { f.aasm.events.map(&:name) }.to_not raise_error end end end describe 'subclasses' do it "should have the same states as its parent class" do expect(DerivateNewDsl.aasm.states).to eq(SimpleNewDsl.aasm.states) end it "should have the same events as its parent class" do expect(DerivateNewDsl.aasm.events).to eq(SimpleNewDsl.aasm.events) end it "should have the same column as its parent even for the new dsl" do expect(SimpleNewDsl.aasm.attribute_name).to eq(:status) expect(DerivateNewDsl.aasm.attribute_name).to eq(:status) end end describe "named scopes with the new DSL" do context "Does not already respond_to? the scope name" do it "should add a scope for each state" do expect(SimpleNewDsl).to respond_to(:unknown_scope) expect(SimpleNewDsl).to respond_to(:another_unknown_scope) expect(SimpleNewDsl.unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy expect(SimpleNewDsl.another_unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy end end context "Already respond_to? the scope name" do it "should not add a scope" do expect(SimpleNewDsl).to respond_to(:new) expect(SimpleNewDsl.new.class).to eq(SimpleNewDsl) end end # Scopes on abstract classes didn't work until Rails 5. # # Reference: # https://github.com/rails/rails/issues/10658 if ActiveRecord::VERSION::MAJOR >= 5 context "For a descendant of an abstract model" do it "should add the scope without the table_name" do expect(ImplementedAbstractClassDsl).to respond_to(:unknown_scope) expect(ImplementedAbstractClassDsl).to respond_to(:another_unknown_scope) expect(ImplementedAbstractClassDsl.unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy expect(ImplementedAbstractClassDsl.another_unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy end end end it "does not create scopes if requested" do expect(NoScope).not_to respond_to(:pending) end context "result of scope" do let!(:dsl1) { SimpleNewDsl.create!(status: :new) } let!(:dsl2) { SimpleNewDsl.create!(status: :unknown_scope) } after do SimpleNewDsl.destroy_all end it "created scope works as where(name: :scope_name)" do expect(SimpleNewDsl.unknown_scope).to contain_exactly(dsl2) end end end # scopes describe "direct assignment" do it "is allowed by default" do obj = NoScope.create expect(obj.aasm_state.to_sym).to eql :pending obj.aasm_state = :running expect(obj.aasm_state.to_sym).to eql :running end it "is forbidden if configured" do obj = NoDirectAssignment.create expect(obj.aasm_state.to_sym).to eql :pending expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :pending end it 'can be turned off and on again' do obj = NoDirectAssignment.create expect(obj.aasm_state.to_sym).to eql :pending expect {obj.aasm_state = :running}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :pending # allow it temporarily NoDirectAssignment.aasm.state_machine.config.no_direct_assignment = false obj.aasm_state = :running expect(obj.aasm_state.to_sym).to eql :running # and forbid it again NoDirectAssignment.aasm.state_machine.config.no_direct_assignment = true expect {obj.aasm_state = :pending}.to raise_error(AASM::NoDirectAssignmentError) expect(obj.aasm_state.to_sym).to eql :running end end # direct assignment describe 'initial states' do it 'should support conditions' do expect(Thief.new(:skilled => true).aasm.current_state).to eq(:rich) expect(Thief.new(:skilled => false).aasm.current_state).to eq(:jailed) end end describe 'transitions with persistence' do it "should work for valid models" do valid_object = Validator.create(:name => 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = Validator.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(ActiveRecord::RecordInvalid) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = SilentPersistor.create(:name => 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = InvalidPersistor.create(:name => 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = InvalidPersistor.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end describe 'pessimistic locking' do let(:worker) { Worker.create!(:name => 'worker', :status => 'sleeping') } subject { transactor.run! } context 'no lock' do let(:transactor) { NoLockTransactor.create!(:name => 'no_lock_transactor', :worker => worker) } it 'should not invoke lock!' do expect(transactor).to_not receive(:lock!) subject end end context 'a default lock' do let(:transactor) { LockTransactor.create!(:name => 'lock_transactor', :worker => worker) } it 'should invoke lock! with true' do expect(transactor).to receive(:lock!).with(true).and_call_original subject end end context 'a FOR UPDATE NOWAIT lock' do let(:transactor) { LockNoWaitTransactor.create!(:name => 'lock_no_wait_transactor', :worker => worker) } it 'should invoke lock! with FOR UPDATE NOWAIT' do expect(transactor).to receive(:lock!).with('FOR UPDATE NOWAIT').and_call_original subject end end end describe 'without transactions' do let(:worker) { Worker.create!(:name => 'worker', :status => 'sleeping') } let(:no_transactor) { NoTransactor.create!(:name => 'transactor', :worker => worker) } it 'should not rollback all changes' do expect(no_transactor).to be_sleeping expect(worker.status).to eq('sleeping') expect {no_transactor.run!}.to raise_error(StandardError, 'failed on purpose') expect(no_transactor).to be_running expect(worker.reload.status).to eq('running') end end describe 'transactions' do let(:worker) { Worker.create!(:name => 'worker', :status => 'sleeping') } let(:transactor) { Transactor.create!(:name => 'transactor', :worker => worker) } it 'should rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') expect {transactor.run!}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end context "nested transactions" do it "should rollback all changes in nested transaction" do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Worker.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('sleeping') end it "should only rollback changes in the main transaction not the nested one" do # change configuration to not require new transaction AASM::StateMachineStore[Transactor][:default].config.requires_new_transaction = false expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') Worker.transaction do expect { transactor.run! }.to raise_error(StandardError, 'failed on purpose') end expect(transactor).to be_running expect(worker.reload.status).to eq('running') end end describe "after_commit callback" do it "should fire :after_commit if transaction was successful" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping validator.run! expect(validator).to be_running expect(validator.name).to eq("name changed") validator.sleep!("sleeper") expect(validator).to be_sleeping expect(validator.name).to eq("sleeper") end it "should not fire :after_commit if transaction failed" do validator = Validator.create(:name => 'name') expect { validator.fail! }.to raise_error(StandardError, 'failed on purpose') expect(validator.name).to eq("name") end it "should not fire :after_commit if validation failed when saving object" do validator = Validator.create(:name => 'name') validator.invalid = true expect { validator.run! }.to raise_error(ActiveRecord::RecordInvalid, 'Invalid record') expect(validator).to be_sleeping expect(validator.name).to eq("name") end it "should not fire if not saving" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping validator.run expect(validator).to be_running expect(validator.name).to eq("name") end context "nested transaction" do it "should fire :after_commit if root transaction was successful" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping validator.transaction do validator.run! expect(validator.name).to eq("name") expect(validator).to be_running end expect(validator.name).to eq("name changed") expect(validator.reload).to be_running end it "should not fire :after_commit if root transaction failed" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping validator.transaction do validator.run! expect(validator.name).to eq("name") expect(validator).to be_running raise ActiveRecord::Rollback, "failed on purpose" end expect(validator.name).to eq("name") expect(validator.reload).to be_sleeping end end end describe 'callbacks for the new DSL' do it "be called in order" do show_debug_log = false callback = ActiveRecordCallback.create callback.aasm.current_state unless show_debug_log expect(callback).to receive(:before_all_events).once.ordered expect(callback).to receive(:before_event).once.ordered expect(callback).to receive(:event_guard).once.ordered.and_return(true) expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:before_exit_open).once.ordered # these should be before the state changes expect(callback).to receive(:exit_open).once.ordered # expect(callback).to receive(:event_guard).once.ordered.and_return(true) # expect(callback).to receive(:transition_guard).once.ordered.and_return(true) expect(callback).to receive(:after_all_transitions).once.ordered expect(callback).to receive(:after_transition).once.ordered expect(callback).to receive(:before_enter_closed).once.ordered expect(callback).to receive(:enter_closed).once.ordered expect(callback).to receive(:aasm_write_state).once.ordered.and_return(true) # this is when the state changes expect(callback).to receive(:after_exit_open).once.ordered # these should be after the state changes expect(callback).to receive(:after_enter_closed).once.ordered expect(callback).to receive(:after_event).once.ordered expect(callback).to receive(:after_all_events).once.ordered expect(callback).to receive(:ensure_event).once.ordered expect(callback).to receive(:ensure_on_all_events).once.ordered expect(callback).to receive(:event_after_commit).once.ordered end callback.close! end end describe 'before and after transaction callbacks' do [:after, :before].each do |event_type| describe "#{event_type}_transaction callback" do it "should fire :#{event_type}_transaction if transaction was successful" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run! }.to change { validator.send("#{event_type}_transaction_performed_on_run") }.from(nil).to(true) expect(validator).to be_running end it "should fire :#{event_type}_transaction if transaction failed" do validator = Validator.create(:name => 'name') expect do begin validator.fail! rescue => ignored end end.to change { validator.send("#{event_type}_transaction_performed_on_fail") }.from(nil).to(true) expect(validator).to_not be_running end it "should fire :#{event_type}_transaction if transaction failed w/ kwarg" do validator = Validator.create(:name => 'name') expect do begin validator.fail_with_reason!(reason: 'reason') rescue => ignored expect(ignored).not_to be_instance_of(ArgumentError) end end.to change { validator.send("#{event_type}_transaction_performed_on_fail_with_reason") }.from(nil).to('reason') expect(validator).to_not be_running end it "should not fire :#{event_type}_transaction if not saving" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run }.to_not change { validator.send("#{event_type}_transaction_performed_on_run") } expect(validator).to be_running expect(validator.name).to eq("name") end end end end describe 'before and after all transactions callbacks' do [:after, :before].each do |event_type| describe "#{event_type}_all_transactions callback" do it "should fire :#{event_type}_all_transactions if transaction was successful" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run! }.to change { validator.send("#{event_type}_all_transactions_performed") }.from(nil).to(true) expect(validator).to be_running end it "should fire :#{event_type}_all_transactions if transaction failed" do validator = Validator.create(:name => 'name') expect do begin validator.fail! rescue => ignored end end.to change { validator.send("#{event_type}_all_transactions_performed") }.from(nil).to(true) expect(validator).to_not be_running end it "should not fire :#{event_type}_all_transactions if not saving" do validator = Validator.create(:name => 'name') expect(validator).to be_sleeping expect { validator.run }.to_not change { validator.send("#{event_type}_all_transactions_performed") } expect(validator).to be_running expect(validator.name).to eq("name") end end end end context "when not persisting" do it 'should not rollback all changes' do expect(transactor).to be_sleeping expect(worker.status).to eq('sleeping') # Notice here we're calling "run" and not "run!" with a bang. expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') expect(transactor).to be_running expect(worker.reload.status).to eq('running') end it 'should not create a database transaction' do expect(transactor.class).not_to receive(:transaction) expect {transactor.run}.to raise_error(StandardError, 'failed on purpose') end end end end describe "invalid states with persistence" do it "should not store states" do validator = Validator.create(:name => 'name') validator.status = 'invalid_state' expect(validator.save).to be_falsey expect {validator.save!}.to raise_error(ActiveRecord::RecordInvalid) validator.reload expect(validator).to be_sleeping end it "should store invalid states if configured" do persistor = InvalidPersistor.create(:name => 'name') persistor.status = 'invalid_state' expect(persistor.save).to be_truthy persistor.reload expect(persistor.status).to eq('invalid_state') end end describe 'basic example with two state machines' do let(:example) { BasicActiveRecordTwoStateMachinesExample.new } it 'should initialise properly' do expect(example.aasm(:search).current_state).to eql :initialised expect(example.aasm(:sync).current_state).to eql :unsynced end end describe 'testing the README examples' do it 'Usage' do job = ReadmeJob.new expect(job.sleeping?).to eql true expect(job.may_run?).to eql true job.run expect(job.running?).to eql true expect(job.sleeping?).to eql false expect(job.may_run?).to eql false expect { job.run }.to raise_error(AASM::InvalidTransition) end end describe 'testing the instance_level skip validation with _without_validation method' do let(:example) do obj = InstanceLevelSkipValidationExample.new(state: 'new') obj.save(validate: false) obj end it 'should be able to change the state with invalid record' do expect(example.valid?).to be_falsey expect(example.complete!).to be_falsey expect(example.complete_without_validation!).to be_truthy expect(example.state).to eq('complete') end it 'shouldn\'t affect the behaviour of existing method after calling _without_validation! method' do expect(example.set_draft!).to be_falsey expect(example.set_draft_without_validation!).to be_truthy expect(example.state).to eq('draft') expect(example.complete!).to be_falsey end end describe 'testing the timestamps option' do let(:example) { TimestampExample.create! } it 'should update existing timestamp columns' do expect { example.open! }.to change { example.reload.opened_at }.from(nil).to(instance_of(::Time)) end it 'should not fail if there is no corresponding timestamp column' do expect { example.close! }.to change { example.reload.aasm_state } end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/dynamoid_persistence_spec.rb
spec/unit/persistence/dynamoid_persistence_spec.rb
require 'spec_helper' if defined?(Dynamoid) describe 'dynamoid' do Dir[File.dirname(__FILE__) + "/../../models/dynamoid/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = DynamoidSimple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm.current_state).to eq(:alpha) end it "should save the initial state" do model.save expect(model.status).to eq("alpha") end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm.current_state).to eq(:beta) end it "should return the aasm column when not new and the aasm_column is not nil" do model.save model.status = "gamma" expect(model.aasm.current_state).to eq(:gamma) end it "should allow a nil state" do model.save model.status = nil expect(model.aasm.current_state).to be_nil end it "should not change the state if state is not loaded" do model.release model.save model.reload expect(model.aasm.current_state).to eq(:beta) end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm.states).to eq(@model.aasm.states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm.events).to eq(@model.aasm.events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm.attribute_name).to eq(:status) expect(Class.new(@model).aasm.attribute_name).to eq(:status) end end describe 'initial states' do it 'should support conditions' do @model.aasm do initial_state lambda{ |m| m.default } end expect(@model.new(:default => :beta).aasm.current_state).to eq(:beta) expect(@model.new(:default => :gamma).aasm.current_state).to eq(:gamma) end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/redis_persistence_spec.rb
spec/unit/persistence/redis_persistence_spec.rb
require 'spec_helper' if defined?(Redis::Objects) describe 'redis' do Dir[File.dirname(__FILE__) + "/../../models/redis/*.rb"].sort.each do |f| require File.expand_path(f) end before(:all) do @model = RedisSimple end describe "instance methods" do let(:model) {@model.new} it "should respond to aasm persistence methods" do expect(model).to respond_to(:aasm_read_state) expect(model).to respond_to(:aasm_write_state) expect(model).to respond_to(:aasm_write_state_without_persistence) end it "should return the initial state when new and the aasm field is nil" do expect(model.aasm.current_state).to eq(:alpha) end it "should return the aasm column when new and the aasm field is not nil" do model.status = "beta" expect(model.aasm.current_state).to eq(:beta) end it "should allow a nil state" do model.status = nil expect(model.aasm.current_state).to be_nil end end describe 'subclasses' do it "should have the same states as its parent class" do expect(Class.new(@model).aasm.states).to eq(@model.aasm.states) end it "should have the same events as its parent class" do expect(Class.new(@model).aasm.events).to eq(@model.aasm.events) end it "should have the same column as its parent even for the new dsl" do expect(@model.aasm.attribute_name).to eq(:status) expect(Class.new(@model).aasm.attribute_name).to eq(:status) end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/persistence/no_brainer_persistence_spec.rb
spec/unit/persistence/no_brainer_persistence_spec.rb
require 'spec_helper' if defined?(NoBrainer::Document) describe 'nobrainer' do Dir[File.dirname(__FILE__) + '/../../models/nobrainer/*.rb'].sort.each do |f| require File.expand_path(f) end before(:all) do # if you want to see the statements while running the spec enable the # following line # NoBrainer.configure do |config| # config.logger = Logger.new(STDERR) # end end after do NoBrainer.purge! end describe 'named scopes with the old DSL' do context 'Does not already respond_to? the scope name' do it 'should add a scope for each state' do expect(SimpleNoBrainer).to respond_to(:unknown_scope) expect(SimpleNoBrainer).to respond_to(:another_unknown_scope) expect(SimpleNoBrainer.unknown_scope.class).to eq(NoBrainer::Criteria) expect(SimpleNoBrainer.another_unknown_scope.class).to eq(NoBrainer::Criteria) end end context 'Already respond_to? the scope name' do it 'should not add a scope' do expect(SimpleNoBrainer).to respond_to(:new) expect(SimpleNoBrainer.new.class).to eq(SimpleNoBrainer) end end end describe 'named scopes with the new DSL' do context 'Does not already respond_to? the scope name' do it 'should add a scope' do expect(SimpleNewDslNoBrainer).to respond_to(:unknown_scope) expect(SimpleNewDslNoBrainer.unknown_scope.class).to eq(NoBrainer::Criteria) end end context 'Already respond_to? the scope name' do it 'should not add a scope' do expect(SimpleNewDslNoBrainer).to respond_to(:new) expect(SimpleNewDslNoBrainer.new.class).to eq(SimpleNewDslNoBrainer) end end it 'does not create scopes if requested' do expect(NoScopeNoBrainer).not_to respond_to(:ignored_scope) end end describe 'instance methods' do let(:simple) { SimpleNewDslNoBrainer.new } it 'should initialize the aasm state on instantiation' do expect(SimpleNewDslNoBrainer.new.status).to eql 'unknown_scope' expect(SimpleNewDslNoBrainer.new.aasm.current_state).to eql :unknown_scope end end describe 'relations object' do it 'should load relations object ids' do parent = Parent.create child_1 = Child.create(parent_id: parent.id) child_2 = Child.create(parent_id: parent.id) expect(parent.childs.pluck(:id, :status).map(&:id)).to eql [child_1.id, child_2.id] end end describe 'transitions with persistence' do it 'should work for valid models' do valid_object = ValidatorNoBrainer.create(name: 'name') expect(valid_object).to be_sleeping valid_object.status = :running expect(valid_object).to be_running end it 'should not store states for invalid models' do validator = ValidatorNoBrainer.create(name: 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect { validator.run! }.to raise_error(NoBrainer::Error::DocumentInvalid) expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should not store states for invalid models silently if configured' do validator = SilentPersistorNoBrainer.create(name: 'name') expect(validator).to be_valid expect(validator).to be_sleeping validator.name = nil expect(validator).not_to be_valid expect(validator.run!).to be_falsey expect(validator).to be_sleeping validator.reload expect(validator).not_to be_running expect(validator).to be_sleeping validator.name = 'another name' expect(validator).to be_valid expect(validator.run!).to be_truthy expect(validator).to be_running validator.reload expect(validator).to be_running expect(validator).not_to be_sleeping end it 'should store states for invalid models if configured' do persistor = InvalidPersistorNoBrainer.create(name: 'name') expect(persistor).to be_valid expect(persistor).to be_sleeping persistor.name = nil expect(persistor).not_to be_valid expect(persistor.run!).to be_truthy expect(persistor).to be_running persistor = InvalidPersistorNoBrainer.find(persistor.id) persistor.valid? expect(persistor).to be_valid expect(persistor).to be_running expect(persistor).not_to be_sleeping persistor.reload expect(persistor).to be_running expect(persistor).not_to be_sleeping end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/invokers/base_invoker_spec.rb
spec/unit/invokers/base_invoker_spec.rb
require 'spec_helper' describe AASM::Core::Invokers::BaseInvoker do let(:target) { double } let(:record) { double } let(:args) { [] } subject { described_class.new(target, record, args) } describe '#may_invoke?' do it 'then raises NoMethodError' do expect { subject.may_invoke? }.to raise_error(NoMethodError) end end describe '#log_failure' do it 'then raises NoMethodError' do expect { subject.log_failure }.to raise_error(NoMethodError) end end describe '#invoke_subject' do it 'then raises NoMethodError' do expect { subject.log_failure }.to raise_error(NoMethodError) end end describe '#with_failures' do it 'then sets failures buffer' do buffer = [1, 2, 3] subject.with_failures(buffer) expect(subject.failures).to eq(buffer) end end describe '#invoke' do context 'when #may_invoke? respond with "false"' do before { allow(subject).to receive(:may_invoke?).and_return(false) } it 'then returns "nil"' do expect(subject.invoke).to eq(nil) end end context 'when #invoke_subject respond with "false"' do before do allow(subject).to receive(:may_invoke?).and_return(true) allow(subject).to receive(:invoke_subject).and_return(false) end it 'then calls #log_failure' do expect(subject).to receive(:log_failure) subject.invoke end end context 'when #invoke_subject succeed' do before do allow(subject).to receive(:may_invoke?).and_return(true) allow(subject).to receive(:invoke_subject).and_return(true) end it 'then returns result' do expect(subject).to receive(:result) subject.invoke end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/invokers/class_invoker_spec.rb
spec/unit/invokers/class_invoker_spec.rb
require 'spec_helper' describe AASM::Core::Invokers::ClassInvoker do let(:target) { Class.new { def call; end } } let(:record) { double } let(:args) { [] } subject { described_class.new(target, record, args) } describe '#may_invoke?' do context 'when subject is a Class and responds to #call' do it 'then returns "true"' do expect(subject.may_invoke?).to eq(true) end end context 'when subject is not a class or not respond to #call' do let(:target) { Class.new {} } it 'then returns "false"' do expect(subject.may_invoke?).to eq(false) end end end describe '#log_failure' do context 'when subject respond to #source_location' do it 'then adds "source_location" to a failures buffer' do subject.log_failure expect(subject.failures) .to eq([target.instance_method(:call).source_location.join('#')]) end end context 'when subject does not respond to #source_location' do before do Method.__send__(:alias_method, :original_source_location, :source_location) Method.__send__(:undef_method, :source_location) end after do Method.__send__( :define_method, :source_location, Method.instance_method(:original_source_location) ) end it 'then adds the subject to a failures buffer' do subject.log_failure expect(subject.failures.first).to be_a(Method) end context 'when a failure occurs' do let(:target) { Class.new { def initialize(_r, *_a); end; def call; end } } it 'only instantiates subject class one time' do target_instance = target.new(record, *args) expect(target).to receive(:new).with(record, *args).and_return(target_instance).once expect { subject.invoke }.not_to raise_error end end end end describe '#invoke_subject' do context 'when passing no arguments' do let(:args) { [1, 2 ,3] } let(:target) { Class.new { def call; end } } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing single argument' do let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { Class.new { def initialize(_a); end; def call; end } } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing variable number arguments' do let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { Class.new { def initialize(_a, _b, *_c); end; def call; end } } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing one or more arguments' do let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { Class.new { def initialize(_a, _b, _c); end; def call; end } } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing keyword arguments' do let(:args) { [1, key: 2] } let(:target) { Class.new { def initialize(record, a, key: nil); end; def call; end } } it 'then correctly uses passed keyword arguments' do expect(target).to receive(:new).with(record, 1, key: 2).and_call_original expect { subject.invoke_subject }.not_to raise_error end end context 'when passing optional keyword arguments' do let(:args) { [1, foo: 1] } let(:target) { Class.new { def initialize(record, a, key: nil, foo:); end; def call; end } } it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing empty optional keyword arguments' do let(:args) { [1] } let(:target) { Class.new { def initialize(record, a, key: nil); end; def call; end } } it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/invokers/literal_invoker_spec.rb
spec/unit/invokers/literal_invoker_spec.rb
require 'spec_helper' describe AASM::Core::Invokers::LiteralInvoker do let(:target) { nil } let(:record) { double } let(:args) { [] } subject { described_class.new(target, record, args) } describe '#may_invoke?' do context 'when subject is a Symbol' do let(:target) { :i_am_symbol } it 'then returns "true"' do expect(subject.may_invoke?).to eq(true) end end context 'when subject is a String' do let(:target) { 'i_am_string' } it 'then returns "true"' do expect(subject.may_invoke?).to eq(true) end end context 'when subject is neither a String nor Symbol' do let(:target) { double } it 'then returns "false"' do expect(subject.may_invoke?).to eq(false) end end end describe '#log_failure' do let(:target) { Proc.new { false } } it 'then adds the subject to a failures buffer' do subject.log_failure expect(subject.failures).to eq([target]) end end describe '#invoke_subject' do context 'when passing no arguments' do let(:record) { Class.new { def my_method; end }.new } let(:args) { [1, 2 ,3] } let(:target) { :my_method } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing variable number arguments' do let(:record) { Class.new { def my_method(_a, _b, *_c); end }.new } let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { :my_method } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing one or more arguments' do let(:record) { Class.new { def my_method(_a, _b, _c); end }.new } let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { :my_method } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when record does not respond to subject' do let(:record) { Class.new { }.new } let(:target) { :my_method } it 'then raises uses passed arguments' do expect { subject.invoke_subject }.to raise_error(NoMethodError) end end context 'when using optional keyword arguments' do let(:args) { [1] } let(:record) { Class.new { def my_method(_a, key: 3); end; }.new } let(:target) { :my_method} it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when using required keyword arguments' do let(:args) { [1, key: 2] } let(:record) { Class.new { def my_method(_a, key:); end; }.new } let(:target) { :my_method} it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/unit/invokers/proc_invoker_spec.rb
spec/unit/invokers/proc_invoker_spec.rb
require 'spec_helper' describe AASM::Core::Invokers::ProcInvoker do let(:target) { Proc.new {} } let(:record) { double } let(:args) { [] } subject { described_class.new(target, record, args) } describe '#may_invoke?' do context 'when subject is a Proc' do it 'then returns "true"' do expect(subject.may_invoke?).to eq(true) end end context 'when subject is not a Proc' do let(:target) { nil } it 'then returns "false"' do expect(subject.may_invoke?).to eq(false) end end end describe '#log_failure' do context 'when subject respond to #source_location' do it 'then adds "source_location" to a failures buffer' do subject.log_failure expect(subject.failures) .to eq([target.source_location.join('#')]) end end context 'when subject does not respond to #source_location' do before do Method.__send__(:alias_method, :original_source_location, :source_location) Method.__send__(:undef_method, :source_location) end after do Method.__send__( :define_method, :source_location, Method.instance_method(:original_source_location) ) end it 'then adds the subject to a failures buffer' do subject.log_failure expect(subject.failures).to eq([target]) end end end describe '#invoke_subject' do context 'when passing no arguments' do let(:args) { [1, 2 ,3] } let(:target) { ->() {} } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing variable number arguments' do let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { ->(_a, _b, *_c) {} } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing one or more arguments' do let(:args) { [1, 2 ,3, 4, 5, 6] } let(:target) { ->(_a, _b, _c) {} } it 'then correctly uses passed arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing keyword arguments' do let(:args) { [1, key: 2] } let(:target) { ->(_a, key: nil) {} } it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing optional keyword arguments' do let(:args) { [1, foo: 1] } let(:target) { ->(_a, key: nil, foo:) {} } it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when passing required keyword arguments like the failing test' do let(:args) { [reason: 'test_reason'] } let(:target) { proc { |reason:, **| @reason = reason } } it 'should pass the keyword arguments correctly' do subject.invoke_subject expect(record.instance_variable_get(:@reason)).to eq('test_reason') end end context 'when passing empty optional keyword arguments' do let(:args) { [1] } let(:target) { ->(_a, key: nil) {} } it 'then correctly uses passed keyword arguments' do expect { subject.invoke_subject }.not_to raise_error end end context 'when using splat args like existing tests' do let(:args) { ['blue', 'jeans'] } it 'should pass all arguments to splat parameter' do received_args = [] target = proc { |*args| received_args.push(*args) } invoker = described_class.new(target, record, args) invoker.invoke_subject expect(received_args).to eq(['blue', 'jeans']) end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/active_record.rb
spec/spec_helpers/active_record.rb
# encoding: utf-8 begin require 'active_record' puts "active_record #{ActiveRecord::VERSION::STRING} gem found, running ActiveRecord specs \e[32m#{'✔'}\e[0m" rescue LoadError puts "active_record gem not found, not running ActiveRecord specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/redis.rb
spec/spec_helpers/redis.rb
# encoding: utf-8 begin require 'redis-objects' require 'redis/objects/version' puts "redis-objects #{Redis::Objects::VERSION} gem found, running Redis specs \e[32m#{'✔'}\e[0m" redis = Redis.new(host: (ENV['REDIS_HOST'] || '127.0.0.1'), port: (ENV['REDIS_PORT'] || 6379)) Redis::Objects.redis = redis RSpec.configure do |c| c.before(:each) do redis.keys('redis_*').each { |k| redis.del k } end end rescue LoadError puts "redis-objects gem not found, not running Redis specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/dynamoid.rb
spec/spec_helpers/dynamoid.rb
# encoding: utf-8 begin require 'dynamoid' puts "dynamoid #{Dynamoid::VERSION} gem found, running Dynamoid specs \e[32m#{'✔'}\e[0m" if Gem::Version.new(Dynamoid::VERSION) >= Gem::Version.new('3.0.0') require 'aws-sdk-dynamodb' else require 'aws-sdk-resources' end ENV['ACCESS_KEY'] ||= 'abcd' ENV['SECRET_KEY'] ||= '1234' Aws.config.update( region: 'us-west-2', credentials: Aws::Credentials.new(ENV['ACCESS_KEY'], ENV['SECRET_KEY']) ) Dynamoid.configure do |config| config.namespace = 'dynamoid_tests' config.endpoint = "http://#{ENV['DYNAMODB_HOST'] || '127.0.0.1'}:" \ "#{ENV['DYNAMODB_PORT'] || 30180}" config.warn_on_scan = false end Dynamoid.logger.level = Logger::FATAL RSpec.configure do |c| c.before(:each) do Dynamoid.adapter.list_tables.each do |table| Dynamoid.adapter.delete_table(table) if table =~ /^#{Dynamoid::Config.namespace}/ end Dynamoid.adapter.tables.clear end end rescue LoadError puts "dynamoid gem not found, not running Dynamoid specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/sequel.rb
spec/spec_helpers/sequel.rb
# encoding: utf-8 begin require 'sequel' puts "sequel #{Sequel::VERSION} gem found, running Sequel specs \e[32m#{'✔'}\e[0m" rescue LoadError puts "sequel gem not found, not running Sequel specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/mongoid.rb
spec/spec_helpers/mongoid.rb
# encoding: utf-8 begin require 'mongoid' require 'rails' puts "mongoid #{Mongoid::VERSION} gem found, running mongoid specs \e[32m#{'✔'}\e[0m" if Mongoid::VERSION.to_f <= 5 Mongoid::Config.sessions = { default: { database: "mongoid_#{Process.pid}", hosts: ["#{ENV['MONGODB_HOST'] || 'localhost'}:" \ "#{ENV['MONGODB_PORT'] || 27017}"] } } else Mongoid::Config.send(:clients=, { default: { database: "mongoid_#{Process.pid}", hosts: ["#{ENV['MONGODB_HOST'] || 'localhost'}:" \ "#{ENV['MONGODB_PORT'] || 27017}"] } }) end rescue LoadError puts "mongoid gem not found, not running mongoid specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/remove_warnings.rb
spec/spec_helpers/remove_warnings.rb
AASM::Configuration.hide_warnings = true
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helpers/nobrainer.rb
spec/spec_helpers/nobrainer.rb
# encoding: utf-8 begin require 'nobrainer' NoBrainer.configure do |config| config.app_name = :aasm config.environment = :test config.warn_on_active_record = false end puts "nobrainer #{Gem.loaded_specs['nobrainer'].version} gem found, running nobrainer specs \e[32m#{'✔'}\e[0m" rescue LoadError puts "nobrainer gem not found, not running nobrainer specs \e[31m#{'✖'}\e[0m" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/motion-aasm.rb
lib/motion-aasm.rb
unless defined?(Motion::Project::App) raise "This must be required from within a RubyMotion Rakefile" end file_dependencies = { 'aasm/aasm.rb' => ['aasm/persistence.rb'], 'aasm/persistence.rb' => ['aasm/persistence/plain_persistence.rb', 'aasm/persistence/core_data_query_persistence.rb'], 'aasm/persistence/base.rb' => ['aasm/base.rb'], 'aasm/persistence/core_data_query_persistence.rb' => ['aasm/persistence/base.rb'] } exclude_files = [ 'aasm/rspec.*', 'aasm/minitest.*', 'aasm/minitest_spec.*', 'aasm/persistence/active_record_persistence.rb', 'aasm/persistence/dynamoid_persistence.rb', 'aasm/persistence/mongoid_persistence.rb', 'aasm/persistence/no_brainer_persistence.rb', 'aasm/persistence/sequel_persistence.rb', 'aasm/persistence/redis_persistence.rb' ] Motion::Project::App.setup do |app| parent = File.expand_path File.dirname(__FILE__) app.files.unshift Dir.glob(File.join(parent, "aasm/**/*.rb")).reject { |file| exclude_files.any? { |exclude| file.match(exclude) } } app.files_dependencies file_dependencies.inject({}, &->(file_dependencies, (file, *dependencies)) do file = File.join(parent, file) dependencies = dependencies.flatten(1).map do |dependency| File.join(parent, dependency) end file_dependencies.merge({ file => dependencies }) end) end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm.rb
lib/aasm.rb
require 'aasm/version' require 'aasm/errors' require 'aasm/configuration' require 'aasm/base' require 'aasm/dsl_helper' require 'aasm/instance_base' require 'aasm/core/transition' require 'aasm/core/event' require 'aasm/core/state' require 'aasm/core/invoker' require 'aasm/core/invokers/base_invoker' require 'aasm/core/invokers/class_invoker' require 'aasm/core/invokers/literal_invoker' require 'aasm/core/invokers/proc_invoker' require 'aasm/localizer' require 'aasm/state_machine_store' require 'aasm/state_machine' require 'aasm/persistence' require 'aasm/persistence/base' require 'aasm/persistence/plain_persistence' require 'aasm/aasm'
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/nobrainer/aasm_generator.rb
lib/generators/nobrainer/aasm_generator.rb
require 'rails/generators/named_base' require 'generators/aasm/orm_helpers' module NoBrainer module Generators class AASMGenerator < Rails::Generators::NamedBase include AASM::Generators::OrmHelpers namespace 'nobrainer:aasm' argument :column_name, type: :string, default: 'aasm_state' def generate_model invoke 'nobrainer:model', [name] unless model_exists? end def inject_aasm_content inject_into_file model_path, model_contents, after: "include NoBrainer::Document::Timestamps\n" if model_exists? end def inject_field_types inject_into_file model_path, migration_data, after: "include NoBrainer::Document::Timestamps\n" if model_exists? end def migration_data " field :#{column_name}" end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/mongoid/aasm_generator.rb
lib/generators/mongoid/aasm_generator.rb
require 'rails/generators/named_base' require 'generators/aasm/orm_helpers' module Mongoid module Generators class AASMGenerator < Rails::Generators::NamedBase include AASM::Generators::OrmHelpers namespace "mongoid:aasm" argument :column_name, type: :string, default: 'aasm_state' def generate_model invoke "mongoid:model", [name] unless model_exists? end def inject_aasm_content inject_into_file model_path, model_contents, after: "include Mongoid::Document\n" if model_exists? end def inject_field_types inject_into_file model_path, migration_data, after: "include Mongoid::Document\n" if model_exists? end def migration_data " field :#{column_name}" end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/aasm/orm_helpers.rb
lib/generators/aasm/orm_helpers.rb
module AASM module Generators module OrmHelpers def model_contents if column_name == 'aasm_state' <<RUBY include AASM aasm do end RUBY else <<RUBY include AASM aasm :column => '#{column_name}' do end RUBY end end private def column_exists? table_name.singularize.humanize.constantize.column_names.include?(column_name.to_s) rescue NameError false end def model_exists? File.exist?(File.join(destination_root, model_path)) end def model_path @model_path ||= File.join("app", "models", "#{file_path}.rb") end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/aasm/aasm_generator.rb
lib/generators/aasm/aasm_generator.rb
require 'rails/generators/named_base' module AASM module Generators class AASMGenerator < Rails::Generators::NamedBase namespace "aasm" argument :column_name, type: :string, default: 'aasm_state' desc "Generates a model with the given NAME (if one does not exist) with aasm " << "block and migration to add aasm_state column." hook_for :orm end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/active_record/aasm_generator.rb
lib/generators/active_record/aasm_generator.rb
require 'rails/generators/active_record' require 'generators/aasm/orm_helpers' module ActiveRecord module Generators class AASMGenerator < ActiveRecord::Generators::Base include AASM::Generators::OrmHelpers namespace "active_record:aasm" argument :column_name, type: :string, default: 'aasm_state' source_root File.expand_path("../templates", __FILE__) def copy_aasm_migration if column_exists? puts "Both model and column exists" elsif model_exists? migration_template "migration_existing.rb", "db/migrate/add_#{column_name}_to_#{table_name}.rb" else migration_template "migration.rb", "db/migrate/aasm_create_#{table_name}.rb" end end def generate_model invoke "active_record:model", [name], migration: false unless model_exists? end def inject_aasm_content content = model_contents class_path = if namespaced? class_name.to_s.split("::") else [class_name] end inject_into_class(model_path, class_path.last, content) if model_exists? end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/active_record/templates/migration_existing.rb
lib/generators/active_record/templates/migration_existing.rb
class Add<%= column_name.camelize %>To<%= table_name.camelize %> < ActiveRecord::Migration[<%= ActiveRecord::VERSION::STRING.to_f %>] def change add_column :<%= table_name %>, :<%= column_name %>, :string end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/generators/active_record/templates/migration.rb
lib/generators/active_record/templates/migration.rb
class AasmCreate<%= table_name.camelize %> < ActiveRecord::Migration[<%= ActiveRecord::VERSION::STRING.to_f %>] def change create_table(:<%= table_name %>) do |t| t.string :<%= column_name %> t.timestamps null: false end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/persistence.rb
lib/aasm/persistence.rb
module AASM module Persistence class << self def load_persistence(base) # Use a fancier auto-loading thingy, perhaps. When there are more persistence engines. hierarchy = base.ancestors.map {|klass| klass.to_s} if hierarchy.include?("ActiveRecord::Base") require_persistence :active_record include_persistence base, :active_record elsif hierarchy.include?("Mongoid::Document") require_persistence :mongoid include_persistence base, :mongoid elsif hierarchy.include?("NoBrainer::Document") require_persistence :no_brainer include_persistence base, :no_brainer elsif hierarchy.include?("Sequel::Model") require_persistence :sequel include_persistence base, :sequel elsif hierarchy.include?("Dynamoid::Document") require_persistence :dynamoid include_persistence base, :dynamoid elsif hierarchy.include?("Redis::Objects") require_persistence :redis include_persistence base, :redis elsif hierarchy.include?("CDQManagedObject") include_persistence base, :core_data_query else include_persistence base, :plain end end private def require_persistence(type) require File.join(File.dirname(__FILE__), 'persistence', "#{type}_persistence") end def include_persistence(base, type) base.send(:include, constantize("#{capitalize(type)}Persistence")) end def capitalize(string_or_symbol) string_or_symbol.to_s.split('_').map {|segment| segment[0].upcase + segment[1..-1]}.join('') end def constantize(string) AASM::Persistence.const_get(string) end end # class << self end end # AASM
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/version.rb
lib/aasm/version.rb
module AASM VERSION = "5.5.2" end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/localizer.rb
lib/aasm/localizer.rb
module AASM class Localizer def human_event_name(klass, event) checklist = ancestors_list(klass).inject([]) do |list, ancestor| list << :"#{i18n_scope(klass)}.events.#{i18n_klass(ancestor)}.#{event}" list end translate_queue(checklist) || I18n.translate(checklist.shift, :default => default_display_name(event)) end def human_state_name(klass, state) checklist = ancestors_list(klass).inject([]) do |list, ancestor| list << item_for(klass, state, ancestor) list << item_for(klass, state, ancestor, :old_style => true) list end translate_queue(checklist) || I18n.translate(checklist.shift, :default => default_display_name(state)) end private def item_for(klass, state, ancestor, options={}) separator = options[:old_style] ? '.' : '/' :"#{i18n_scope(klass)}.attributes.#{i18n_klass(ancestor)}.#{klass.aasm(state.state_machine.name).attribute_name}#{separator}#{state}" end def translate_queue(checklist) (0...(checklist.size-1)).each do |i| begin return I18n.translate(checklist.shift, :raise => true) rescue I18n::MissingTranslationData # that's okay end end nil end # added for rails 2.x compatibility def i18n_scope(klass) klass.respond_to?(:i18n_scope) ? klass.i18n_scope : :activerecord end # added for rails < 3.0.3 compatibility def i18n_klass(klass) klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore end def ancestors_list(klass) has_active_record_base = defined?(::ActiveRecord::Base) klass.ancestors.select do |ancestor| not_active_record_base = has_active_record_base ? (ancestor != ::ActiveRecord::Base) : true ancestor.respond_to?(:model_name) && not_active_record_base end end def default_display_name(object) # Can use better arguement name if object.respond_to?(:default_display_name) object.default_display_name else object.to_s.gsub(/_/, ' ').capitalize end end end end # AASM
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/state_machine.rb
lib/aasm/state_machine.rb
module AASM class StateMachine # the following four methods provide the storage of all state machines attr_accessor :states, :events, :initial_state, :config, :name, :global_callbacks def initialize(name) @initial_state = nil @states = [] @events = {} @global_callbacks = {} @config = AASM::Configuration.new @name = name end # called internally by Ruby 1.9 after clone() def initialize_copy(orig) super @states = orig.states.collect { |state| state.clone } @events = {} orig.events.each_pair { |name, event| @events[name] = event.clone } @global_callbacks = @global_callbacks.dup end def add_state(state_name, klass, options) set_initial_state(state_name, options) # allow reloading, extending or redefining a state @states.delete(state_name) if @states.include?(state_name) @states << AASM::Core::State.new(state_name, klass, self, options) end def add_event(name, options, &block) @events[name] = AASM::Core::Event.new(name, self, options, &block) end def add_global_callbacks(name, *callbacks, &block) @global_callbacks[name] ||= [] callbacks.each do |callback| @global_callbacks[name] << callback unless @global_callbacks[name].include? callback end @global_callbacks[name] << block if block end private def set_initial_state(name, options) @initial_state = name if options[:initial] || !initial_state end end # StateMachine end # AASM
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/errors.rb
lib/aasm/errors.rb
module AASM class UnknownStateMachineError < RuntimeError; end class InvalidTransition < RuntimeError attr_reader :object, :event_name, :originating_state, :failures, :state_machine_name def initialize(object, event_name, state_machine_name, failures = []) @object, @event_name, @originating_state, @failures = object, event_name, object.aasm(state_machine_name).current_state, failures @state_machine_name = state_machine_name super("Event '#{event_name}' cannot transition from '#{originating_state}'.#{reasoning}") end def reasoning " Failed callback(s): #{failures}." unless failures.empty? end end class UndefinedState < RuntimeError; end class UndefinedEvent < UndefinedState; end class NoDirectAssignmentError < RuntimeError; end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest_spec.rb
lib/aasm/minitest_spec.rb
require 'aasm/minitest' module Minitest::Expectations AASM.infect_an_assertion :assert_transitions_from, :must_transition_from, :do_not_flip AASM.infect_an_assertion :refute_transitions_from, :wont_transition_from, :do_not_flip AASM.infect_an_assertion :assert_transition_to_allowed, :must_allow_transition_to, :do_not_flip AASM.infect_an_assertion :refute_transition_to_allowed, :wont_allow_transition_to, :do_not_flip AASM.infect_an_assertion :assert_have_state, :must_have_state, :do_not_flip AASM.infect_an_assertion :refute_have_state, :wont_have_state, :do_not_flip AASM.infect_an_assertion :assert_event_allowed, :must_allow_event, :do_not_flip AASM.infect_an_assertion :refute_event_allowed, :wont_allow_event, :do_not_flip end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/state_machine_store.rb
lib/aasm/state_machine_store.rb
require 'concurrent/map' module AASM class StateMachineStore @stores = Concurrent::Map.new class << self def stores @stores end # do not overwrite existing state machines, which could have been created by # inheritance, see AASM::ClassMethods method inherited def register(klass, overwrite = false, state_machine = nil) raise "Cannot register #{klass}" unless klass.is_a?(Class) case name = template = overwrite when FalseClass then stores[klass.to_s] ||= new when TrueClass then stores[klass.to_s] = new when Class then stores[klass.to_s] = stores[template.to_s].clone when Symbol then stores[klass.to_s].register(name, state_machine) when String then stores[klass.to_s].register(name, state_machine) else raise "Don't know what to do with #{overwrite}" end end alias_method :[]=, :register def fetch(klass, fallback = nil) stores[klass.to_s] || fallback && begin match = klass.ancestors.find do |ancestor| ancestor.include? AASM and stores[ancestor.to_s] end stores[match.to_s] end end alias_method :[], :fetch def unregister(klass) stores.delete(klass.to_s) end end def initialize @machines = Concurrent::Map.new end def clone StateMachineStore.new.tap do |store| @machines.each_pair do |name, machine| store.register(name, machine.clone) end end end def machine(name) @machines[name.to_s] end alias_method :[], :machine def machine_names @machines.keys end alias_method :keys, :machine_names def register(name, machine, force = false) raise "Cannot use #{name.inspect} for machine name" unless name.is_a?(Symbol) or name.is_a?(String) raise "Cannot use #{machine.inspect} as a machine" unless machine.is_a?(AASM::StateMachine) if force @machines[name.to_s] = machine else @machines[name.to_s] ||= machine end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/instance_base.rb
lib/aasm/instance_base.rb
module AASM class InstanceBase attr_accessor :from_state, :to_state, :current_event def initialize(instance, name=:default) # instance of the class including AASM, name of the state machine @instance = instance @name = name end def current_state @instance.aasm_read_state(@name) end def current_state=(state) @instance.aasm_write_state_without_persistence(state, @name) end def enter_initial_state state_name = determine_state_name(@instance.class.aasm(@name).initial_state) state_object = state_object_for_name(state_name) state_object.fire_callbacks(:before_enter, @instance) self.current_state = state_name state_object.fire_callbacks(:after_enter, @instance) state_name end def human_state state_object_for_name(current_state).display_name end def states(options={}, *args) if options.has_key?(:permitted) selected_events = events({:permitted => options[:permitted]}, *args) # An array of arrays. Each inner array represents the transitions that # transition from the current state for an event event_transitions = selected_events.map {|e| e.transitions_from_state(current_state) } # An array of :to transition states to_state_names = event_transitions.map do |transitions| return nil if transitions.empty? # Return the :to state of the first transition that is allowed (or not) or nil if options[:permitted] transition = transitions.find { |t| t.allowed?(@instance, *args) } else transition = transitions.find { |t| !t.allowed?(@instance, *args) } end transition ? transition.to : nil end.flatten.compact.uniq # Select states that are in to_state_names @instance.class.aasm(@name).states.select {|s| to_state_names.include?(s.name)} else @instance.class.aasm(@name).states end end def events(options={}, *args) state = options[:state] || current_state events = @instance.class.aasm(@name).events.select {|e| e.transitions_from_state?(state) } options[:reject] = Array(options[:reject]) events.reject! { |e| options[:reject].include?(e.name) } if options.has_key?(:permitted) # filters the results of events_for_current_state so that only those that # are really currently possible (given transition guards) are shown. if options[:permitted] events.select! { |e| @instance.send("may_#{e.name}?", *args) } else events.select! { |e| !@instance.send("may_#{e.name}?", *args) } end end events end def permitted_transitions events(permitted: true).flat_map do |event| available_transitions = event.transitions_from_state(current_state) allowed_transitions = available_transitions.select { |t| t.allowed?(@instance) } allowed_transitions.map do |transition| { event: event.name, state: transition.to } end end end def state_object_for_name(name) obj = @instance.class.aasm(@name).states.find {|s| s.name == name} raise AASM::UndefinedState, "State :#{name} doesn't exist" if obj.nil? obj end def determine_state_name(state) case state when Symbol, String state when Proc state.call(@instance) else raise NotImplementedError, "Unrecognized state-type given. Expected Symbol, String, or Proc." end end def may_fire_event?(name, *args) if event = @instance.class.aasm(@name).state_machine.events[name] !!event.may_fire?(@instance, *args) else false # unknown event end end def fire(event_name, *args, &block) event_exists?(event_name) @instance.send(event_name, *args, &block) end def fire!(event_name, *args, &block) event_exists?(event_name, true) bang_event_name = "#{event_name}!".to_sym @instance.send(bang_event_name, *args, &block) end def set_current_state_with_persistence(state) save_success = @instance.aasm_write_state(state, @name) self.current_state = state if save_success save_success end private def event_exists?(event_name, bang = false) event = @instance.class.aasm(@name).state_machine.events[event_name.to_sym] return true if event event_error = bang ? "#{event_name}!" : event_name raise AASM::UndefinedEvent, "Event :#{event_error} doesn't exist" if event.nil? end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/base.rb
lib/aasm/base.rb
require 'logger' module AASM class Base attr_reader :klass, :state_machine def initialize(klass, name, state_machine, options={}, &block) @klass = klass @name = name # @state_machine = klass.aasm(@name).state_machine @state_machine = state_machine @state_machine.config.column ||= (options[:column] || default_column).to_sym # @state_machine.config.column = options[:column].to_sym if options[:column] # master @options = options # let's cry if the transition is invalid configure :whiny_transitions, true # create named scopes for each state configure :create_scopes, true # don't store any new state if the model is invalid (in ActiveRecord) configure :skip_validation_on_save, false # raise if the model is invalid (in ActiveRecord) configure :whiny_persistence, false # Use transactions (in ActiveRecord) configure :use_transactions, true # use requires_new for nested transactions (in ActiveRecord) configure :requires_new_transaction, true # use pessimistic locking (in ActiveRecord) # true for FOR UPDATE lock # string for a specific lock type i.e. FOR UPDATE NOWAIT configure :requires_lock, false # automatically set `"#{state_name}_at" = ::Time.now` on state changes configure :timestamps, false # set to true to forbid direct assignment of aasm_state column (in ActiveRecord) configure :no_direct_assignment, false # allow a AASM::Base sub-class to be used for state machine configure :with_klass, AASM::Base configure :enum, nil # Set to true to namespace reader methods and constants configure :namespace, false # Configure a logger, with default being a Logger to STDERR configure :logger, Logger.new(STDERR) # setup timestamp-setting callback if enabled setup_timestamps(@name) # make sure to raise an error if no_direct_assignment is enabled # and attribute is directly assigned though setup_no_direct_assignment(@name) end # This method is both a getter and a setter def attribute_name(column_name=nil) if column_name @state_machine.config.column = column_name.to_sym else @state_machine.config.column ||= :aasm_state end @state_machine.config.column end def initial_state(new_initial_state=nil) if new_initial_state @state_machine.initial_state = new_initial_state else @state_machine.initial_state end end # define a state # args # [0] state # [1] options (or nil) # or # [0] state # [1..] state def state(*args) names, options = interpret_state_args(args) names.each do |name| @state_machine.add_state(name, klass, options) aasm_name = @name.to_sym state = name.to_sym method_name = namespace? ? "#{namespace}_#{name}" : name safely_define_method klass, "#{method_name}?", -> do aasm(aasm_name).current_state == state end const_name = namespace? ? "STATE_#{namespace.upcase}_#{name.upcase}" : "STATE_#{name.upcase}" unless klass.const_defined?(const_name) klass.const_set(const_name, name) end end end # define an event def event(name, options={}, &block) @state_machine.add_event(name, options, &block) aasm_name = @name.to_sym event = name.to_sym # an addition over standard aasm so that, before firing an event, you can ask # may_event? and get back a boolean that tells you whether the guard method # on the transition will let this happen. safely_define_method klass, "may_#{name}?", ->(*args) do aasm(aasm_name).may_fire_event?(event, *args) end safely_define_method klass, "#{name}!", ->(*args, &block) do aasm(aasm_name).current_event = :"#{name}!" aasm_fire_event(aasm_name, event, {:persist => true}, *args, &block) end safely_define_method klass, name, ->(*args, &block) do aasm(aasm_name).current_event = event aasm_fire_event(aasm_name, event, {:persist => false}, *args, &block) end skip_instance_level_validation(event, name, aasm_name, klass) # Create aliases for the event methods. Keep the old names to maintain backwards compatibility. if namespace? klass.send(:alias_method, "may_#{name}_#{namespace}?", "may_#{name}?") klass.send(:alias_method, "#{name}_#{namespace}!", "#{name}!") klass.send(:alias_method, "#{name}_#{namespace}", name) end end def after_all_transitions(*callbacks, &block) @state_machine.add_global_callbacks(:after_all_transitions, *callbacks, &block) end def after_all_transactions(*callbacks, &block) @state_machine.add_global_callbacks(:after_all_transactions, *callbacks, &block) end def before_all_transactions(*callbacks, &block) @state_machine.add_global_callbacks(:before_all_transactions, *callbacks, &block) end def before_all_events(*callbacks, &block) @state_machine.add_global_callbacks(:before_all_events, *callbacks, &block) end def after_all_events(*callbacks, &block) @state_machine.add_global_callbacks(:after_all_events, *callbacks, &block) end def error_on_all_events(*callbacks, &block) @state_machine.add_global_callbacks(:error_on_all_events, *callbacks, &block) end def ensure_on_all_events(*callbacks, &block) @state_machine.add_global_callbacks(:ensure_on_all_events, *callbacks, &block) end def states @state_machine.states end def events @state_machine.events.values end # aasm.event(:event_name).human? def human_event_name(event) # event_name? AASM::Localizer.new.human_event_name(klass, event) end def states_for_select states.map { |state| state.for_select } end def from_states_for_state(state, options={}) if options[:transition] @state_machine.events[options[:transition]].transitions_to_state(state).flatten.map(&:from).flatten else events.map {|e| e.transitions_to_state(state)}.flatten.map(&:from).flatten end end private def default_column @name.to_sym == :default ? :aasm_state : @name.to_sym end def configure(key, default_value) if @options.key?(key) @state_machine.config.send("#{key}=", @options[key]) elsif @state_machine.config.send(key).nil? @state_machine.config.send("#{key}=", default_value) end end def safely_define_method(klass, method_name, method_definition) # Warn if method exists and it did not originate from an enum if klass.method_defined?(method_name) && ! ( @state_machine.config.enum && klass.respond_to?(:defined_enums) && klass.defined_enums.values.any?{ |methods| methods.keys{| enum | enum + '?' == method_name } }) unless AASM::Configuration.hide_warnings @state_machine.config.logger.warn "#{klass.name}: overriding method '#{method_name}'!" end end klass.send(:define_method, method_name, method_definition).tap do |sym| apply_ruby2_keyword(klass, sym) end end def apply_ruby2_keyword(klass, sym) if RUBY_VERSION >= '2.7.1' if klass.instance_method(sym).parameters.find { |type, _| type.to_s.start_with?('rest') } # If there is a place where you are receiving in *args, do ruby2_keywords. klass.module_eval do ruby2_keywords sym end end end end def namespace? !!@state_machine.config.namespace end def namespace if @state_machine.config.namespace == true @name else @state_machine.config.namespace end end def interpret_state_args(args) if args.last.is_a?(Hash) && args.size == 2 [[args.first], args.last] elsif args.size > 0 [args, {}] else raise "count not parse states: #{args}" end end def skip_instance_level_validation(event, name, aasm_name, klass) # Overrides the skip_validation config for an instance (If skip validation is set to false in original config) and # restores it back to the original value after the event is fired. safely_define_method klass, "#{name}_without_validation!", ->(*args, &block) do original_config = AASM::StateMachineStore.fetch(self.class, true).machine(aasm_name).config.skip_validation_on_save begin AASM::StateMachineStore.fetch(self.class, true).machine(aasm_name).config.skip_validation_on_save = true unless original_config aasm(aasm_name).current_event = :"#{name}!" aasm_fire_event(aasm_name, event, {:persist => true}, *args, &block) ensure AASM::StateMachineStore.fetch(self.class, true).machine(aasm_name).config.skip_validation_on_save = original_config end end end def setup_timestamps(aasm_name) return unless @state_machine.config.timestamps after_all_transitions do if self.class.aasm(:"#{aasm_name}").state_machine.config.timestamps ts_setter = "#{aasm(aasm_name).to_state}_at=" respond_to?(ts_setter) && send(ts_setter, ::Time.now) end end end def setup_no_direct_assignment(aasm_name) return unless @state_machine.config.no_direct_assignment @klass.send(:define_method, "#{@state_machine.config.column}=") do |state_name| if self.class.aasm(:"#{aasm_name}").state_machine.config.no_direct_assignment raise AASM::NoDirectAssignmentError.new('direct assignment of AASM column has been disabled (see AASM configuration for this class)') else super(state_name) end end end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/configuration.rb
lib/aasm/configuration.rb
module AASM class Configuration # for all persistence layers: which database column to use? attr_accessor :column # let's cry if the transition is invalid attr_accessor :whiny_transitions # for all persistence layers: create named scopes for each state attr_accessor :create_scopes # for ActiveRecord: when the model is invalid, true -> raise, false -> return false attr_accessor :whiny_persistence # for ActiveRecord: store the new state even if the model is invalid and return true attr_accessor :skip_validation_on_save # for ActiveRecord: use transactions attr_accessor :use_transactions # for ActiveRecord: use requires_new for nested transactions? attr_accessor :requires_new_transaction # for ActiveRecord: use pessimistic locking attr_accessor :requires_lock # automatically set `"#{state_name}_at" = ::Time.now` on state changes attr_accessor :timestamps # forbid direct assignment in aasm_state column (in ActiveRecord) attr_accessor :no_direct_assignment # allow a AASM::Base sub-class to be used for state machine attr_accessor :with_klass attr_accessor :enum # namespace reader methods and constants attr_accessor :namespace # Configure a logger, with default being a Logger to STDERR attr_accessor :logger class << self attr_accessor :hide_warnings end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/minitest.rb
lib/aasm/minitest.rb
Minitest = MiniTest unless defined? Minitest # relative-require all minitest_spec files Dir[File.dirname(__FILE__) + '/minitest/*.rb'].each do |file| require 'aasm/minitest/' + File.basename(file, File.extname(file)) end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/rspec.rb
lib/aasm/rspec.rb
# relative-require all rspec files Dir[File.dirname(__FILE__) + '/rspec/*.rb'].each do |file| require 'aasm/rspec/' + File.basename(file, File.extname(file)) end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false
aasm/aasm
https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/lib/aasm/aasm.rb
lib/aasm/aasm.rb
module AASM # this is used internally as an argument default value to represent no value NO_VALUE = :_aasm_no_value # provide a state machine for the including class # make sure to load class methods as well # initialize persistence for the state machine def self.included(base) #:nodoc: base.extend AASM::ClassMethods # do not overwrite existing state machines, which could have been created by # inheritance, see class method inherited AASM::StateMachineStore.register(base) AASM::Persistence.load_persistence(base) super end module ClassMethods # make sure inheritance (aka subclassing) works with AASM def inherited(base) AASM::StateMachineStore.register(base, self) super end # this is the entry point for all state and event definitions def aasm(*args, &block) if args[0].is_a?(Symbol) || args[0].is_a?(String) # using custom name state_machine_name = args[0].to_sym options = args[1] || {} else # using the default state_machine_name state_machine_name = :default options = args[0] || {} end AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name)) # use a default despite the DSL configuration default. # this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class. aasm_klass = options[:with_klass] || AASM::Base raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base) @aasm ||= Concurrent::Map.new if @aasm[state_machine_name] # make sure to use provided options options.each do |key, value| @aasm[state_machine_name].state_machine.config.send("#{key}=", value) end else # create a new base @aasm[state_machine_name] = aasm_klass.new( self, state_machine_name, AASM::StateMachineStore.fetch(self, true).machine(state_machine_name), options ) end @aasm[state_machine_name].instance_eval(&block) if block # new DSL @aasm[state_machine_name] end end # ClassMethods # this is the entry point for all instance-level access to AASM def aasm(name=:default) unless AASM::StateMachineStore.fetch(self.class, true).machine(name) raise AASM::UnknownStateMachineError.new("There is no state machine with the name '#{name}' defined in #{self.class.name}!") end @aasm ||= Concurrent::Map.new @aasm[name.to_sym] ||= AASM::InstanceBase.new(self, name.to_sym) end def initialize_dup(other) @aasm = Concurrent::Map.new super end private # Takes args and a from state and removes the first # element from args if it is a valid to_state for # the event given the from_state def process_args(event, from_state, *args) # If the first arg doesn't respond to to_sym then # it isn't a symbol or string so it can't be a state # name anyway return args unless args.first.respond_to?(:to_sym) if event.transitions_from_state(from_state).map(&:to).flatten.include?(args.first) return args[1..-1] end return args end def aasm_fire_event(state_machine_name, event_name, options, *args, &block) event = self.class.aasm(state_machine_name).state_machine.events[event_name] begin old_state = aasm(state_machine_name).state_object_for_name(aasm(state_machine_name).current_state) fire_default_callbacks(event, *process_args(event, aasm(state_machine_name).current_state, *args)) if may_fire_to = event.may_fire?(self, *args) fire_exit_callbacks(old_state, *process_args(event, aasm(state_machine_name).current_state, *args)) if new_state_name = event.fire(self, {:may_fire => may_fire_to}, *args) aasm_fired(state_machine_name, event, old_state, new_state_name, options, *args, &block) else aasm_failed(state_machine_name, event_name, old_state, event.failed_callbacks) end else aasm_failed(state_machine_name, event_name, old_state, event.failed_callbacks) end rescue StandardError => e event.fire_callbacks(:error, self, e, *process_args(event, aasm(state_machine_name).current_state, *args)) || event.fire_global_callbacks(:error_on_all_events, self, e, *process_args(event, aasm(state_machine_name).current_state, *args)) || raise(e) false ensure event.fire_callbacks(:ensure, self, *process_args(event, aasm(state_machine_name).current_state, *args)) event.fire_global_callbacks(:ensure_on_all_events, self, *process_args(event, aasm(state_machine_name).current_state, *args)) end end def fire_default_callbacks(event, *processed_args) event.fire_global_callbacks( :before_all_events, self, *processed_args ) # new event before callback event.fire_callbacks( :before, self, *processed_args ) end def fire_exit_callbacks(old_state, *processed_args) old_state.fire_callbacks(:before_exit, self, *processed_args) old_state.fire_callbacks(:exit, self, *processed_args) end def aasm_fired(state_machine_name, event, old_state, new_state_name, options, *args) persist = options[:persist] new_state = aasm(state_machine_name).state_object_for_name(new_state_name) callback_args = process_args(event, aasm(state_machine_name).current_state, *args) new_state.fire_callbacks(:before_enter, self, *callback_args) new_state.fire_callbacks(:enter, self, *callback_args) # TODO: remove for AASM 4? persist_successful = true if persist persist_successful = aasm(state_machine_name).set_current_state_with_persistence(new_state_name) if persist_successful yield if block_given? event.fire_callbacks(:before_success, self, *callback_args) event.fire_transition_callbacks(self, *process_args(event, old_state.name, *args)) event.fire_callbacks(:success, self, *callback_args) end else aasm(state_machine_name).current_state = new_state_name yield if block_given? end binding_event = event.options[:binding_event] if binding_event __send__("#{binding_event}#{'!' if persist}") end if persist_successful old_state.fire_callbacks(:after_exit, self, *callback_args) new_state.fire_callbacks(:after_enter, self, *callback_args) event.fire_callbacks( :after, self, *process_args(event, old_state.name, *args) ) event.fire_global_callbacks( :after_all_events, self, *process_args(event, old_state.name, *args) ) self.aasm_event_fired(event.name, old_state.name, aasm(state_machine_name).current_state) if self.respond_to?(:aasm_event_fired) else self.aasm_event_failed(event.name, old_state.name) if self.respond_to?(:aasm_event_failed) end persist_successful end def aasm_failed(state_machine_name, event_name, old_state, failures = []) if self.respond_to?(:aasm_event_failed) self.aasm_event_failed(event_name, old_state.name) end if AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.whiny_transitions raise AASM::InvalidTransition.new(self, event_name, state_machine_name, failures) else false end end end
ruby
MIT
726a578808e0f403bfd24e505f9a45319670a6b7
2026-01-04T15:43:55.088186Z
false