|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require_relative 'test_helper' |
| 4 | + |
| 5 | +class MachineInitializationCompatibilityTest < BaseTestCase |
| 6 | + def setup |
| 7 | + @model = new_model do |
| 8 | + include ActiveModel::Validations |
| 9 | + attr_accessor :state |
| 10 | + end |
| 11 | + |
| 12 | + @machine = StateMachines::Machine.new(@model, initial: :parked) |
| 13 | + @machine.state :parked, :idling |
| 14 | + @machine.event :ignite |
| 15 | + end |
| 16 | + |
| 17 | + def test_should_accept_positional_hash_argument |
| 18 | + record = @model.new({ state: 'idling' }) |
| 19 | + assert_equal 'idling', record.state |
| 20 | + end |
| 21 | + |
| 22 | + def test_should_accept_keyword_arguments |
| 23 | + record = @model.new(state: 'idling') |
| 24 | + assert_equal 'idling', record.state |
| 25 | + end |
| 26 | + |
| 27 | + def test_should_accept_empty_initialization |
| 28 | + record = @model.new |
| 29 | + assert_equal 'parked', record.state |
| 30 | + end |
| 31 | + |
| 32 | + def test_should_handle_attribute_aliases |
| 33 | + @model.class_eval do |
| 34 | + def self.attribute_aliases |
| 35 | + { 'status' => 'state' } |
| 36 | + end |
| 37 | + end |
| 38 | + |
| 39 | + record = @model.new(status: 'idling') |
| 40 | + assert_equal 'idling', record.state |
| 41 | + end |
| 42 | + |
| 43 | + def test_should_prefer_positional_hash_over_keywords_when_both_present |
| 44 | + # If someone accidentally provides both, positional takes precedence |
| 45 | + record = @model.new({ state: 'idling' }, state: 'parked') |
| 46 | + assert_equal 'idling', record.state |
| 47 | + end |
| 48 | + |
| 49 | + def test_should_handle_empty_positional_hash |
| 50 | + # Empty hash should still be treated as positional argument |
| 51 | + record = @model.new({}) |
| 52 | + assert_equal 'parked', record.state # Gets default initial state |
| 53 | + end |
| 54 | + |
| 55 | + def test_should_use_keywords_when_empty_hash_and_keywords_present |
| 56 | + # With the fix, keywords are ignored even with empty positional hash |
| 57 | + record = @model.new({}, state: 'idling') |
| 58 | + assert_equal 'parked', record.state # Empty hash takes precedence |
| 59 | + end |
| 60 | +end |
0 commit comments