Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Use result as errors base if it responds to

Oliver Güntherc20302492aa5
diff --git a/app/services/service_result.rb b/app/services/service_result.rb
index f22a576ef74..e06ed7a838c 100644
--- a/app/services/service_result.rb
+++ b/app/services/service_result.rb
@@ -83,7 +83,7 @@ class ServiceResult
self.result = result
self.state = state
- initialize_errors(errors)
+ initialize_errors(errors, result)
@message = message
@message_type = message_type
@@ -232,13 +232,14 @@ class ServiceResult
private
- def initialize_errors(errors)
- self.errors = errors || new_errors_with_result
+ def initialize_errors(errors, provided_result)
+ self.errors = errors || new_errors_with_result(provided_result)
end
- def new_errors_with_result
- ActiveModel::Errors.new(self).tap do |errors|
- errors.merge!(result) if result.try(:errors).present?
+ def new_errors_with_result(provided_result)
+ base = provided_result.respond_to?(:errors) ? provided_result : self
+ ActiveModel::Errors.new(base).tap do |errors|
+ errors.merge!(provided_result) if base != self
end
end
diff --git a/spec/services/service_result_spec.rb b/spec/services/service_result_spec.rb
index f51f66e3a17..36fdcd3a6ca 100644
--- a/spec/services/service_result_spec.rb
+++ b/spec/services/service_result_spec.rb
@@ -161,6 +161,38 @@ RSpec.describe ServiceResult, type: :model do
expect { instance.errors.full_messages }.not_to raise_error
end
end
+
+ context "when providing active record result" do
+ let(:result) { build(:work_package) }
+
+ it "creates a new errors instance" do
+ instance = described_class.new(result:)
+ base = instance.errors.instance_eval { @base } # rubocop:disable RSpec/InstanceVariable
+ expect(base).to eq(result)
+ end
+ end
+
+ context "when providing some other result" do
+ let(:result) { "wat?" }
+
+ it "creates a new errors instance" do
+ instance = described_class.new(result:)
+ base = instance.errors.instance_eval { @base } # rubocop:disable RSpec/InstanceVariable
+ expect(base).to eq(instance)
+ end
+ end
+
+ context "when using default errors from result" do
+ let(:result) { build(:work_package) }
+
+ it "uses the result's human_attribute_name" do
+ instance = described_class.new(result:)
+ instance.errors.add(:base, "some error")
+ instance.errors.add(:foo, "an error for foo")
+
+ expect { instance.errors.full_messages }.not_to raise_error
+ end
+ end
end
describe "result" do