Module: StateMachines::TestHelper

Defined in:
lib/state_machines/test_helper.rb

Overview

Test helper module providing assertion methods for state machine testing Designed to work with Minitest, RSpec, and future testing frameworks

Examples:

Basic usage with Minitest

class MyModelTest < Minitest::Test
  include StateMachines::TestHelper

  def test_initial_state
    model = MyModel.new
    assert_state(model, :state_machine_name, :initial_state)
  end
end

Usage with RSpec

RSpec.describe MyModel do
  include StateMachines::TestHelper

  it "starts in initial state" do
    model = MyModel.new
    assert_state(model, :state_machine_name, :initial_state)
  end
end

Since:

  • 0.10.0

Instance Method Summary collapse

Instance Method Details

#assert_after_transition(machine_or_class, options = {}, message = nil) ⇒ void

This method returns an undefined value.

Assert that an after_transition callback is defined with expected arguments

Examples:

# Check for specific transition callback
assert_after_transition(Vehicle, on: :crash, do: :tow)

# Check with from/to states
assert_after_transition(Vehicle.state_machine, from: :stalled, to: :parked, do: :log_repair)

Parameters:

  • machine_or_class (StateMachines::Machine, Class)

    The machine or class to check

  • options (Hash) (defaults to: {})

    Expected callback options (on:, from:, to:, do:, if:, unless:)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the callback is not defined

Since:

  • 0.10.0



459
460
461
# File 'lib/state_machines/test_helper.rb', line 459

def assert_after_transition(machine_or_class, options = {}, message = nil)
  _assert_transition_callback(:after, machine_or_class, options, message)
end

#assert_before_transition(machine_or_class, options = {}, message = nil) ⇒ void

This method returns an undefined value.

Assert that a before_transition callback is defined with expected arguments

Examples:

# Check for specific transition callback
assert_before_transition(Vehicle, on: :crash, do: :emergency_stop)

# Check with from/to states
assert_before_transition(Vehicle.state_machine, from: :parked, to: :idling, do: :start_engine)

# Check with conditions
assert_before_transition(Vehicle, on: :ignite, if: :seatbelt_on?)

Parameters:

  • machine_or_class (StateMachines::Machine, Class)

    The machine or class to check

  • options (Hash) (defaults to: {})

    Expected callback options (on:, from:, to:, do:, if:, unless:)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the callback is not defined

Since:

  • 0.10.0



441
442
443
# File 'lib/state_machines/test_helper.rb', line 441

def assert_before_transition(machine_or_class, options = {}, message = nil)
  _assert_transition_callback(:before, machine_or_class, options, message)
end

#assert_sm_all_sync(object, message = nil) ⇒ void

This method returns an undefined value.

Assert that an object has no async-enabled state machines

Examples:

sync_only_vehicle = Vehicle.new  # All machines are sync-only
assert_sm_all_sync(sync_only_vehicle)

Parameters:

  • object (Object)

    The object with state machines

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If any machine has async mode enabled

Since:

  • 0.10.0



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/state_machines/test_helper.rb', line 528

def assert_sm_all_sync(object, message = nil)
  async_machines = []

  object.class.state_machines.each do |name, machine|
    if machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
      async_machines << name
    end
  end

  default_message = "Expected all state machines to be sync-only, but these have async enabled: #{async_machines.inspect}"

  if defined?(::Minitest)
    assert_empty async_machines, message || default_message
  elsif defined?(::RSpec)
    expect(async_machines).to be_empty, message || default_message
  elsif async_machines.any?
    raise default_message
  end
end

#assert_sm_async_event_methods(object, event, message = nil) ⇒ void

This method returns an undefined value.

Assert that individual async event methods are available

Examples:

drone = AutonomousDrone.new
assert_sm_async_event_methods(drone, :launch)  # Checks launch_async and launch_async!

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event name

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If async event methods are not available

Since:

  • 0.10.0



745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
# File 'lib/state_machines/test_helper.rb', line 745

def assert_sm_async_event_methods(object, event, message = nil)
  async_method = "#{event}_async".to_sym
  async_bang_method = "#{event}_async!".to_sym

  has_async = object.respond_to?(async_method)
  has_async_bang = object.respond_to?(async_bang_method)


  if defined?(::Minitest)
    assert has_async, "Missing #{async_method} method"
    assert has_async_bang, "Missing #{async_bang_method} method"
  elsif defined?(::RSpec)
    expect(has_async).to be_truthy, "Missing #{async_method} method"
    expect(has_async_bang).to be_truthy, "Missing #{async_bang_method} method"
  else
    raise "Missing #{async_method} method" unless has_async
    raise "Missing #{async_bang_method} method" unless has_async_bang
  end
end

#assert_sm_async_methods(object, message = nil) ⇒ void

This method returns an undefined value.

Assert that async methods are available on an async-enabled object

Examples:

drone = AutonomousDrone.new  # Has async: true machines
assert_sm_async_methods(drone)

Parameters:

  • object (Object)

    The object with state machines

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If async methods are not available

Since:

  • 0.10.0



673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/state_machines/test_helper.rb', line 673

def assert_sm_async_methods(object, message = nil)
  async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
  available_async_methods = async_methods.select { |method| object.respond_to?(method) }

  default_message = "Expected async methods to be available, but found none"

  if defined?(::Minitest)
    refute_empty available_async_methods, message || default_message
  elsif defined?(::RSpec)
    expect(available_async_methods).not_to be_empty, message || default_message
  elsif available_async_methods.empty?
    raise default_message
  end
end

#assert_sm_async_mode(object, machine_name = :state, message = nil) ⇒ void

This method returns an undefined value.

Assert that a state machine is operating in asynchronous mode

Examples:

drone = AutonomousDrone.new
assert_sm_async_mode(drone)                         # Uses default :state machine
assert_sm_async_mode(drone, :teleporter_status)     # Uses :teleporter_status machine

Parameters:

  • object (Object)

    The object with state machines

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the machine doesn’t have async mode enabled

Since:

  • 0.10.0



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/state_machines/test_helper.rb', line 647

def assert_sm_async_mode(object, machine_name = :state, message = nil)
  machine = object.class.state_machines[machine_name]
  raise ArgumentError, "No state machine '#{machine_name}' found" unless machine

  async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
  default_message = "Expected state machine '#{machine_name}' to have async mode enabled, but it's in sync mode"

  if defined?(::Minitest)
    assert async_enabled, message || default_message
  elsif defined?(::RSpec)
    expect(async_enabled).to be_truthy, message || default_message
  else
    raise default_message unless async_enabled
  end
end

#assert_sm_callback_executed(object, callback_name, message = nil) ⇒ Object

Since:

  • 0.10.0



304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/state_machines/test_helper.rb', line 304

def assert_sm_callback_executed(object, callback_name, message = nil)
  callbacks_executed = object.instance_variable_get(:@_sm_callbacks_executed) || []
  callback_was_executed = callbacks_executed.include?(callback_name)
  default_message = "Expected callback #{callback_name} to be executed"

  if defined?(::Minitest)
    assert callback_was_executed, message || default_message
  elsif defined?(::RSpec)
    expect(callback_was_executed).to be_truthy, message || default_message
  else
    raise default_message unless callback_was_executed
  end
end

#assert_sm_can_transition(object, event, machine_name: :state, message: nil) ⇒ void

This method returns an undefined value.

Assert that an object can transition via a specific event

Examples:

user = User.new
assert_sm_can_transition(user, :activate)                         # Uses default :state machine
assert_sm_can_transition(user, :activate, machine_name: :status)  # Uses :status machine

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event name

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the transition is not available

Since:

  • 0.10.0



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/state_machines/test_helper.rb', line 80

def assert_sm_can_transition(object, event, machine_name: :state, message: nil)
  # Try different method naming patterns
  possible_methods = [
    "can_#{event}?",                    # Default state machine or non-namespaced
    "can_#{event}_#{machine_name}?"     # Namespaced events
  ]

  can_method = possible_methods.find { |method| object.respond_to?(method) }

  unless can_method
    available_methods = object.methods.grep(/^can_.*\?$/).sort
    raise ArgumentError, "No transition method found for event :#{event} on machine :#{machine_name}. Available methods: #{available_methods.first(10).inspect}"
  end

  default_message = "Expected to be able to trigger event :#{event} on #{machine_name}, but #{can_method} returned false"

  if defined?(::Minitest)
    assert object.send(can_method), message || default_message
  elsif defined?(::RSpec)
    expect(object.send(can_method)).to be_truthy, message || default_message
  else
    raise default_message unless object.send(can_method)
  end
end

#assert_sm_cannot_transition(object, event, machine_name: :state, message: nil) ⇒ void

This method returns an undefined value.

Assert that an object cannot transition via a specific event

Examples:

user = User.new
assert_sm_cannot_transition(user, :delete)                         # Uses default :state machine
assert_sm_cannot_transition(user, :delete, machine_name: :status)  # Uses :status machine

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event name

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the transition is available

Since:

  • 0.10.0



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/state_machines/test_helper.rb', line 118

def assert_sm_cannot_transition(object, event, machine_name: :state, message: nil)
  # Try different method naming patterns
  possible_methods = [
    "can_#{event}?",                    # Default state machine or non-namespaced
    "can_#{event}_#{machine_name}?"     # Namespaced events
  ]

  can_method = possible_methods.find { |method| object.respond_to?(method) }

  unless can_method
    available_methods = object.methods.grep(/^can_.*\?$/).sort
    raise ArgumentError, "No transition method found for event :#{event} on machine :#{machine_name}. Available methods: #{available_methods.first(10).inspect}"
  end

  default_message = "Expected not to be able to trigger event :#{event} on #{machine_name}, but #{can_method} returned true"

  if defined?(::Minitest)
    refute object.send(can_method), message || default_message
  elsif defined?(::RSpec)
    expect(object.send(can_method)).to be_falsy, message || default_message
  elsif object.send(can_method)
    raise default_message
  end
end

#assert_sm_event_raises_error(object, event, error_class, message = nil) ⇒ Object

Since:

  • 0.10.0



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/state_machines/test_helper.rb', line 285

def assert_sm_event_raises_error(object, event, error_class, message = nil)
  default_message = "Expected event #{event} to raise #{error_class}"

  if defined?(::Minitest)
    assert_raises(error_class, message || default_message) do
      object.send("#{event}!")
    end
  elsif defined?(::RSpec)
    expect { object.send("#{event}!") }.to raise_error(error_class), message || default_message
  else
    begin
      object.send("#{event}!")
      raise default_message
    rescue error_class
      # Expected behavior
    end
  end
end

#assert_sm_event_triggers(object, event, machine_name = :state, message = nil) ⇒ Object

Since:

  • 0.10.0



250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/state_machines/test_helper.rb', line 250

def assert_sm_event_triggers(object, event, machine_name = :state, message = nil)
  initial_state = object.send(machine_name)
  object.send("#{event}!")
  state_changed = initial_state != object.send(machine_name)
  default_message = "Expected event #{event} to trigger state change on #{machine_name}"

  if defined?(::Minitest)
    assert state_changed, message || default_message
  elsif defined?(::RSpec)
    expect(state_changed).to be_truthy, message || default_message
  else
    raise default_message unless state_changed
  end
end

#assert_sm_final_state(machine, state, message = nil) ⇒ Object

Since:

  • 0.10.0



205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/state_machines/test_helper.rb', line 205

def assert_sm_final_state(machine, state, message = nil)
  state_obj = machine.states[state]
  is_final = state_obj&.final?
  default_message = "Expected state #{state} to be final"

  if defined?(::Minitest)
    assert is_final, message || default_message
  elsif defined?(::RSpec)
    expect(is_final).to be_truthy, message || default_message
  else
    raise default_message unless is_final
  end
end

#assert_sm_has_async(object, machine_names = nil, message = nil) ⇒ void

This method returns an undefined value.

Assert that an object has async-enabled state machines

Examples:

drone = AutonomousDrone.new
assert_sm_has_async(drone, [:status, :teleporter_status, :shields])

Parameters:

  • object (Object)

    The object with state machines

  • machine_names (Array<Symbol>) (defaults to: nil)

    Expected async machine names

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If expected machines don’t have async mode

Since:

  • 0.10.0



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/state_machines/test_helper.rb', line 699

def assert_sm_has_async(object, machine_names = nil, message = nil)
  if machine_names
    # Check specific machines
    non_async_machines = machine_names.reject do |name|
      machine = object.class.state_machines[name]
      machine&.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
    end

    default_message = "Expected machines #{machine_names.inspect} to have async enabled, but these don't: #{non_async_machines.inspect}"

    if defined?(::Minitest)
      assert_empty non_async_machines, message || default_message
    elsif defined?(::RSpec)
      expect(non_async_machines).to be_empty, message || default_message
    elsif non_async_machines.any?
      raise default_message
    end
  else
    # Check that at least one machine has async
    async_machines = object.class.state_machines.select do |name, machine|
      machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
    end

    default_message = "Expected at least one state machine to have async enabled, but none found"

    if defined?(::Minitest)
      refute_empty async_machines, message || default_message
    elsif defined?(::RSpec)
      expect(async_machines).not_to be_empty, message || default_message
    elsif async_machines.empty?
      raise default_message
    end
  end
end

#assert_sm_immediate_execution(object, event, machine_name = :state, message = nil) ⇒ void

This method returns an undefined value.

Assert that event execution is immediate (no async delay)

Examples:

car = Car.new
assert_sm_immediate_execution(car, :start)

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event to trigger

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If execution appears to be async

Since:

  • 0.10.0



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'lib/state_machines/test_helper.rb', line 605

def assert_sm_immediate_execution(object, event, machine_name = :state, message = nil)
  initial_state = object.send(machine_name)

  # Record start time and execute
  start_time = Time.now
  object.send("#{event}!")
  execution_time = Time.now - start_time

  final_state = object.send(machine_name)
  state_changed = initial_state != final_state

  # Should complete very quickly (under 10ms for sync operations)
  is_immediate = execution_time < 0.01

  default_message = "Expected immediate sync execution of '#{event}', but took #{execution_time}s (likely async)"

  if defined?(::Minitest)
    assert state_changed, "Event should trigger state change"
    assert is_immediate, message || default_message
  elsif defined?(::RSpec)
    expect(state_changed).to be_truthy, "Event should trigger state change"
    expect(is_immediate).to be_truthy, message || default_message
  else
    raise "Event should trigger state change" unless state_changed
    raise default_message unless is_immediate
  end
end

#assert_sm_initial_state(machine, expected_state, message = nil) ⇒ Object

Since:

  • 0.10.0



191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/state_machines/test_helper.rb', line 191

def assert_sm_initial_state(machine, expected_state, message = nil)
  state_obj = machine.state(expected_state)
  is_initial = state_obj&.initial?
  default_message = "Expected state #{expected_state} to be the initial state"

  if defined?(::Minitest)
    assert is_initial, message || default_message
  elsif defined?(::RSpec)
    expect(is_initial).to be_truthy, message || default_message
  else
    raise default_message unless is_initial
  end
end

#assert_sm_no_async_methods(object, message = nil) ⇒ void

This method returns an undefined value.

Assert that async methods are not available on a sync-only object

Examples:

sync_only_car = Car.new  # Car has no async: true machines
assert_sm_no_async_methods(sync_only_car)

Parameters:

  • object (Object)

    The object with state machines

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If async methods are available

Since:

  • 0.10.0



503
504
505
506
507
508
509
510
511
512
513
514
515
516
# File 'lib/state_machines/test_helper.rb', line 503

def assert_sm_no_async_methods(object, message = nil)
  async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
  available_async_methods = async_methods.select { |method| object.respond_to?(method) }

  default_message = "Expected no async methods to be available, but found: #{available_async_methods.inspect}"

  if defined?(::Minitest)
    assert_empty available_async_methods, message || default_message
  elsif defined?(::RSpec)
    expect(available_async_methods).to be_empty, message || default_message
  elsif available_async_methods.any?
    raise default_message
  end
end

#assert_sm_possible_transitions(machine, from:, expected_to_states:, message: nil) ⇒ Object

Since:

  • 0.10.0



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/state_machines/test_helper.rb', line 219

def assert_sm_possible_transitions(machine, from:, expected_to_states:, message: nil)
  actual_transitions = machine.events.flat_map do |event|
    event.branches.select { |branch| branch.known_states.include?(from) }
         .map(&:to)
  end.uniq
  default_message = "Expected transitions from #{from} to #{expected_to_states} but got #{actual_transitions}"

  if defined?(::Minitest)
    assert_equal expected_to_states.sort, actual_transitions.sort, message || default_message
  elsif defined?(::RSpec)
    expect(actual_transitions.sort).to eq(expected_to_states.sort), message || default_message
  else
    raise default_message unless expected_to_states.sort == actual_transitions.sort
  end
end

#assert_sm_state(object, expected_state, machine_name: :state, message: nil) ⇒ void

This method returns an undefined value.

Assert that an object is in a specific state for a given state machine

Examples:

user = User.new
assert_sm_state(user, :active)                              # Uses default :state machine
assert_sm_state(user, :active, machine_name: :status)       # Uses :status machine

Parameters:

  • object (Object)

    The object with state machines

  • expected_state (Symbol)

    The expected state

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the state doesn’t match

Since:

  • 0.10.0



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/state_machines/test_helper.rb', line 42

def assert_sm_state(object, expected_state, machine_name: :state, message: nil)
  name_method = "#{machine_name}_name"

  # Handle the case where machine_name doesn't have a corresponding _name method
  unless object.respond_to?(name_method)
    available_machines = begin
      object.class.state_machines.keys
    rescue StandardError
      []
    end
    raise ArgumentError, "No state machine '#{machine_name}' found. Available machines: #{available_machines.inspect}"
  end

  actual = object.send(name_method)
  default_message = "Expected #{object.class}##{machine_name} to be #{expected_state}, but was #{actual}"

  if defined?(::Minitest)
    assert_equal expected_state.to_s, actual.to_s, message || default_message
  elsif defined?(::RSpec)
    expect(actual.to_s).to eq(expected_state.to_s), message || default_message
  else
    raise "Expected #{expected_state}, but got #{actual}" unless expected_state.to_s == actual.to_s
  end
end

#assert_sm_state_persisted(record, expected, machine_name = :state, message = nil) ⇒ void

This method returns an undefined value.

Assert that a record’s state is persisted correctly for a specific state machine

Examples:

# Default state machine
assert_sm_state_persisted(user, "active")

# Specific state machine
assert_sm_state_persisted(ship, "up", :shields)
assert_sm_state_persisted(ship, "armed", :weapons)

Parameters:

  • record (Object)

    The record to check (should respond to reload)

  • expected (String, Symbol)

    The expected persisted state

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the persisted state doesn’t match

Since:

  • 0.10.0



349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/state_machines/test_helper.rb', line 349

def assert_sm_state_persisted(record, expected, machine_name = :state, message = nil)
  record.reload if record.respond_to?(:reload)
  actual_state = record.send(machine_name)
  default_message = "Expected persisted state #{expected} for #{machine_name} but got #{actual_state}"

  if defined?(::Minitest)
    assert_equal expected, actual_state, message || default_message
  elsif defined?(::RSpec)
    expect(actual_state).to eq(expected), message || default_message
  else
    raise default_message unless expected == actual_state
  end
end

#assert_sm_states_list(machine, expected_states, message = nil) ⇒ Object

Extended State Machine Assertions ===

Since:

  • 0.10.0



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/state_machines/test_helper.rb', line 164

def assert_sm_states_list(machine, expected_states, message = nil)
  actual_states = machine.states.map(&:name).compact
  default_message = "Expected states #{expected_states} but got #{actual_states}"

  if defined?(::Minitest)
    assert_equal expected_states.sort, actual_states.sort, message || default_message
  elsif defined?(::RSpec)
    expect(actual_states.sort).to eq(expected_states.sort), message || default_message
  else
    raise default_message unless expected_states.sort == actual_states.sort
  end
end

#assert_sm_sync_execution(object, event, expected_state, machine_name = :state, message = nil) ⇒ void

This method returns an undefined value.

Assert that synchronous event execution works correctly

Examples:

car = Car.new
assert_sm_sync_execution(car, :start, :running)
assert_sm_sync_execution(car, :turn_on, :active, :alarm)

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event to trigger

  • expected_state (Symbol)

    The expected state after transition

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If sync execution fails

Since:

  • 0.10.0



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/state_machines/test_helper.rb', line 562

def assert_sm_sync_execution(object, event, expected_state, machine_name = :state, message = nil)
  # Store initial state
  initial_state = object.send(machine_name)

  # Execute event synchronously
  result = object.send("#{event}!")

  # Verify immediate state change (no async delay)
  final_state = object.send(machine_name)

  # Check that transition succeeded
  state_changed = initial_state != final_state
  correct_final_state = final_state.to_s == expected_state.to_s

  default_message = "Expected sync execution of '#{event}' to change #{machine_name} from '#{initial_state}' to '#{expected_state}', but got '#{final_state}'"

  if defined?(::Minitest)
    assert result, "Event #{event} should return true on success"
    assert state_changed, "State should change from #{initial_state}"
    assert correct_final_state, message || default_message
  elsif defined?(::RSpec)
    expect(result).to be_truthy, "Event #{event} should return true on success"
    expect(state_changed).to be_truthy, "State should change from #{initial_state}"
    expect(correct_final_state).to be_truthy, message || default_message
  else
    raise "Event #{event} should return true on success" unless result
    raise "State should change from #{initial_state}" unless state_changed
    raise default_message unless correct_final_state
  end
end

#assert_sm_sync_mode(object, machine_name = :state, message = nil) ⇒ void

This method returns an undefined value.

Assert that a state machine is operating in synchronous mode

Examples:

user = User.new
assert_sm_sync_mode(user)                           # Uses default :state machine
assert_sm_sync_mode(user, :status)                  # Uses :status machine

Parameters:

  • object (Object)

    The object with state machines

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the machine has async mode enabled

Since:

  • 0.10.0



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/state_machines/test_helper.rb', line 477

def assert_sm_sync_mode(object, machine_name = :state, message = nil)
  machine = object.class.state_machines[machine_name]
  raise ArgumentError, "No state machine '#{machine_name}' found" unless machine

  async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
  default_message = "Expected state machine '#{machine_name}' to be in sync mode, but async mode is enabled"

  if defined?(::Minitest)
    refute async_enabled, message || default_message
  elsif defined?(::RSpec)
    expect(async_enabled).to be_falsy, message || default_message
  elsif async_enabled
    raise default_message
  end
end

#assert_sm_thread_safe_methods(object, message = nil) ⇒ void

This method returns an undefined value.

Assert that an object has thread-safe state methods when async is enabled

Examples:

drone = AutonomousDrone.new
assert_sm_thread_safe_methods(drone)

Parameters:

  • object (Object)

    The object with state machines

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If thread-safe methods are not available

Since:

  • 0.10.0



775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'lib/state_machines/test_helper.rb', line 775

def assert_sm_thread_safe_methods(object, message = nil)
  thread_safe_methods = %i[state_machine_mutex read_state_safely write_state_safely]
  missing_methods = thread_safe_methods.reject { |method| object.respond_to?(method) }

  default_message = "Expected thread-safe methods to be available, but missing: #{missing_methods.inspect}"

  if defined?(::Minitest)
    assert_empty missing_methods, message || default_message
  elsif defined?(::RSpec)
    expect(missing_methods).to be_empty, message || default_message
  elsif missing_methods.any?
    raise default_message
  end
end

#assert_sm_transition(object, event, expected_state, machine_name: :state, message: nil) ⇒ void

This method returns an undefined value.

Assert that triggering an event changes the object to the expected state

Examples:

user = User.new
assert_sm_transition(user, :activate, :active)                           # Uses default :state machine
assert_sm_transition(user, :activate, :active, machine_name: :status)    # Uses :status machine

Parameters:

  • object (Object)

    The object with state machines

  • event (Symbol)

    The event to trigger

  • expected_state (Symbol)

    The expected state after transition

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the transition fails or results in wrong state

Since:

  • 0.10.0



157
158
159
160
# File 'lib/state_machines/test_helper.rb', line 157

def assert_sm_transition(object, event, expected_state, machine_name: :state, message: nil)
  object.send("#{event}!")
  assert_sm_state(object, expected_state, machine_name: machine_name, message: message)
end

#assert_sm_triggers_event(object, expected_events, machine_name: :state, message: nil) ⇒ void Also known as: expect_to_trigger_event, have_triggered_event

This method returns an undefined value.

Assert that executing a block triggers one or more expected events

Examples:

# Single event
assert_sm_triggers_event(vehicle, :crash) { vehicle.redline }

# Multiple events
assert_sm_triggers_event(vehicle, [:crash, :emergency]) { vehicle.emergency_stop }

# Specific machine
assert_sm_triggers_event(vehicle, :disable, machine_name: :alarm) { vehicle.turn_off_alarm }

Parameters:

  • object (Object)

    The object with state machines

  • expected_events (Symbol, Array<Symbol>)

    The event(s) expected to be triggered

  • machine_name (Symbol) (defaults to: :state)

    The name of the state machine (defaults to :state)

  • message (String, nil) (defaults to: nil)

    Custom failure message

Raises:

  • (AssertionError)

    If the expected events were not triggered

Since:

  • 0.10.0



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/state_machines/test_helper.rb', line 381

def assert_sm_triggers_event(object, expected_events, machine_name: :state, message: nil)
  expected_events = Array(expected_events)
  triggered_events = []

  # Get the state machine
  machine = object.class.state_machines[machine_name]
  raise ArgumentError, "No state machine found for #{machine_name}" unless machine

  # Save original callbacks to restore later
  machine.callbacks[:before].dup

  # Add a temporary callback to track triggered events
  temp_callback = machine.before_transition do |_obj, transition|
    triggered_events << transition.event if transition.event
  end

  begin
    # Execute the block
    yield

    # Check if expected events were triggered
    missing_events = expected_events - triggered_events
    extra_events = triggered_events - expected_events

    unless missing_events.empty? && extra_events.empty?
      default_message = "Expected events #{expected_events.inspect} to be triggered, but got #{triggered_events.inspect}"
      default_message += ". Missing: #{missing_events.inspect}" if missing_events.any?
      default_message += ". Extra: #{extra_events.inspect}" if extra_events.any?

      if defined?(::Minitest)
        assert false, message || default_message
      elsif defined?(::RSpec)
        raise message || default_message
      else
        raise default_message
      end
    end
  ensure
    # Restore original callbacks by removing the temporary one
    machine.callbacks[:before].delete(temp_callback)
  end
end

#refute_sm_callback_executed(object, callback_name, message = nil) ⇒ Object Also known as: assert_sm_callback_not_executed

Since:

  • 0.10.0



318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/state_machines/test_helper.rb', line 318

def refute_sm_callback_executed(object, callback_name, message = nil)
  callbacks_executed = object.instance_variable_get(:@_sm_callbacks_executed) || []
  callback_was_executed = callbacks_executed.include?(callback_name)
  default_message = "Expected callback #{callback_name} to not be executed"

  if defined?(::Minitest)
    refute callback_was_executed, message || default_message
  elsif defined?(::RSpec)
    expect(callback_was_executed).to be_falsy, message || default_message
  elsif callback_was_executed
    raise default_message
  end
end

#refute_sm_event_triggers(object, event, machine_name = :state, message = nil) ⇒ Object Also known as: assert_sm_event_not_triggers

Since:

  • 0.10.0



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/state_machines/test_helper.rb', line 265

def refute_sm_event_triggers(object, event, machine_name = :state, message = nil)
  initial_state = object.send(machine_name)
  begin
    object.send("#{event}!")
    state_unchanged = initial_state == object.send(machine_name)
    default_message = "Expected event #{event} to not trigger state change on #{machine_name}"

    if defined?(::Minitest)
      assert state_unchanged, message || default_message
    elsif defined?(::RSpec)
      expect(state_unchanged).to be_truthy, message || default_message
    else
      raise default_message unless state_unchanged
    end
  rescue StateMachines::InvalidTransition
    # Expected behavior - transition was blocked
  end
end

#refute_sm_state_defined(machine, state, message = nil) ⇒ Object Also known as: assert_sm_state_not_defined

Since:

  • 0.10.0



177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/state_machines/test_helper.rb', line 177

def refute_sm_state_defined(machine, state, message = nil)
  state_exists = machine.states.any? { |s| s.name == state }
  default_message = "Expected state #{state} to not be defined in machine"

  if defined?(::Minitest)
    refute state_exists, message || default_message
  elsif defined?(::RSpec)
    expect(state_exists).to be_falsy, message || default_message
  elsif state_exists
    raise default_message
  end
end

#refute_sm_transition_allowed(machine, from:, to:, on:, message: nil) ⇒ Object Also known as: assert_sm_transition_not_allowed

Since:

  • 0.10.0



235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/state_machines/test_helper.rb', line 235

def refute_sm_transition_allowed(machine, from:, to:, on:, message: nil)
  event = machine.events[on]
  is_allowed = event&.branches&.any? { |branch| branch.known_states.include?(from) && branch.to == to }
  default_message = "Expected transition from #{from} to #{to} on #{on} to not be allowed"

  if defined?(::Minitest)
    refute is_allowed, message || default_message
  elsif defined?(::RSpec)
    expect(is_allowed).to be_falsy, message || default_message
  elsif is_allowed
    raise default_message
  end
end