From 5ac5b5ebde31da43eb1c5d0abc2e54221d0de939 Mon Sep 17 00:00:00 2001 From: Jorge Manrubia Date: Fri, 16 May 2025 15:38:22 +0200 Subject: [PATCH] Add test for the composite command --- app/models/command/composite.rb | 4 +-- test/models/command/composite_test.rb | 52 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 test/models/command/composite_test.rb diff --git a/app/models/command/composite.rb b/app/models/command/composite.rb index 798a5e8ce..7595e52b9 100644 --- a/app/models/command/composite.rb +++ b/app/models/command/composite.rb @@ -12,7 +12,7 @@ class Command::Composite < Command def undo ApplicationRecord.transaction do - undoable_commands.reverse.each(&:undo) + undoable_commands.collect { it.undo } end end @@ -40,6 +40,6 @@ class Command::Composite < Command end def undoable_commands - @undoable_commands ||= commands.filter(&:undoable?) + @undoable_commands ||= commands.filter(&:undoable?).reverse end end diff --git a/test/models/command/composite_test.rb b/test/models/command/composite_test.rb new file mode 100644 index 000000000..593c92aba --- /dev/null +++ b/test/models/command/composite_test.rb @@ -0,0 +1,52 @@ +require "test_helper" + +class Command::CompositeTest < ActionDispatch::IntegrationTest + include CommandTestHelper + + test "execute commands in order and return an array with the results" do + command = Command::Composite.new(commands: [ build_command(result: "1"), build_command(result: "2") ]) + assert_equal [ "1", "2" ], command.execute + end + + test "undo the commands in reverse order" do + command = Command::Composite.new(commands: [ build_command(result: "1", undoable: true), build_command(result: "2", undoable: true) ]) + assert_equal [ "2", "1" ], command.undo + end + + test "undoable if some of the commands is" do + assert_not Command::Composite.new(commands: [ build_command(undoable: false), build_command(undoable: false) ]).undoable? + assert Command::Composite.new(commands: [ build_command(undoable: true), build_command(undoable: false) ]).undoable? + end + + test "needs confirmation if some of the command does" do + assert_not Command::Composite.new(commands: [ build_command(needs_confirmation: false), build_command(needs_confirmation: false) ]).needs_confirmation? + assert Command::Composite.new(commands: [ build_command(needs_confirmation: true), build_command(needs_confirmation: false) ]).needs_confirmation? + end + + private + def build_command(...) + TestCommand.new(...) + end + + class TestCommand < Command + attribute :result + attribute :undoable + attribute :needs_confirmation + + def execute + result + end + + def undo + result + end + + def undoable? + undoable + end + + def needs_confirmation? + needs_confirmation + end + end +end