Skip to content

Commit

Permalink
ensure_state_may_transition_to! to actually check if attribute can tr…
Browse files Browse the repository at this point in the history
…ansition
  • Loading branch information
Stanislav (Stas) Katkov committed Jun 15, 2024
1 parent 5555bbe commit e157e3a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/state_machine_enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def state_machine_enum(attribute_name, **options_for_enum)
define_method(:"ensure_#{attribute_name}_may_transition_to!") do |next_state|
val = self[attribute_name]
raise InvalidState, "#{attribute_name} already is #{val.inspect}" if next_state.to_s == val
raise InvalidState, "#{attribute_name} may not transition from #{val.inspect} to #{next_state.inspect}" unless collector.may_transition?(val, next_state)
end

define_method(:"#{attribute_name}_may_transition_to?") do |next_state|
Expand Down
7 changes: 4 additions & 3 deletions test/test_state_machine_enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ def test_ensure_state_may_transition_to!
assert_nil u.ensure_state_may_transition_to!(:banned)

assert_raises(StateMachineEnum::InvalidState) { u.ensure_state_may_transition_to!("active") }
assert_raises(StateMachineEnum::InvalidState) { u.ensure_state_may_transition_to!(:active) }
error = assert_raises(StateMachineEnum::InvalidState) { u.ensure_state_may_transition_to!(:active) }
assert_equal("state already is \"active\"", error.message)

# TODO: This method will not actually check if state can transition to the target state, it only verifies that this is not a current state.
# assert_raises(StateMachineEnum::InvalidState) { u.ensure_state_may_transition_to!(:registered) }
error = assert_raises(StateMachineEnum::InvalidState) { u.ensure_state_may_transition_to!(:registered) }
assert_equal("state may not transition from \"active\" to :registered", error.message)
end

def test_ensure_state_one_of!
Expand Down

0 comments on commit e157e3a

Please sign in to comment.