Skip to content

A platform for community discussion. Free, open, simple.

DEV: Preserve existing errors in service model steps (#41896)

Martin Brennanea74b65aa51b
diff --git a/docs/developer-guides/docs/03-code-internals/19-service-objects.md b/docs/developer-guides/docs/03-code-internals/19-service-objects.md
index 948ecce8762..175b4c63d93 100644
--- a/docs/developer-guides/docs/03-code-internals/19-service-objects.md
+++ b/docs/developer-guides/docs/03-code-internals/19-service-objects.md
@@ -106,7 +106,7 @@ This is the generic step, you provide a name, and it will run the defined method
This specialized step helps to remove some boilerplate when dealing with models. By default, it will execute the method named `fetch_<name>`. In the above example, you can see we name our model `:user` and the corresponding method is named `fetch_user`.
-Here, you can fetch (or instantiate) a model as you see fit. If the step returns a falsy value, or an exception is raised, then the execution flow will stop here. If an `ActiveRecord` model is returned, it will call `#invalid?` on it to determine whether the model is valid. If not, the execution flow will stop.
+Here, you can fetch (or instantiate) a model as you see fit. If the step returns a falsy value, or an exception is raised, then the execution flow will stop here. If an `ActiveRecord` model with unsaved changes is returned, the step also fails when the model contains errors or its validations fail. If not, the execution flow will stop.
This step is also compatible with collections: if a collection is fetched but empty, the execution flow will stop.
@@ -363,7 +363,9 @@ This step cannot fail.
This step helps to remove some boilerplate when fetching/instantiating models or a collection of models. A model can be pretty much anything (not only `ActiveRecord` models), being a single object or a collection. The result of the step will be stored in the context as `name` (so, by default, it would be `context[:model]`).
-The step will fail if the model is `nil`, empty, invalid (in the case of an `ActiveRecord` object) or if an exception is raised. Its result object can be inspected by accessing the `result.model.<name>` key of the main result object. The model result object exposes one or two keys:
+The step will fail if the model is `nil` or `empty?`, or if an exception is raised. In the case of an `ActiveRecord` object with unsaved changes, the step also fails if the model already contains errors (a record whose save failed, for example) — those errors are preserved for `on_model_errors` — or otherwise if running its validations marks it as invalid. Models without pending changes are not revalidated, and non-`ActiveRecord` objects are never validated.
+
+Its result object can be inspected by accessing the `result.model.<name>` key of the main result object. The model result object exposes one or two keys:
- _invalid_: will be `true` if the model has been found but is invalid.
- _not_found_: will be `true` if the model was not found.
@@ -578,7 +580,7 @@ Will execute the provided block if the model named `name` is not present. It als
- _name_: the name of the model to match. Defaults to `model`.
-Will execute the provided block if the model named `name` contains validation errors. It also provides the actual model as the first argument of the block.
+Will execute the provided block if the model named `name` contains errors. It also provides the actual model as the first argument of the block.
### `on_exceptions(*exceptions)`
diff --git a/lib/service/base/model_step.rb b/lib/service/base/model_step.rb
index 5fdd0f8669e..6bc304eedd5 100644
--- a/lib/service/base/model_step.rb
+++ b/lib/service/base/model_step.rb
@@ -15,9 +15,10 @@ module Service
end
def run_step
- context[name] = super
- raise NotFound if !optional && (!context[name] || context[name].try(:empty?))
- if context[name].try(:has_changes_to_save?) && context[name].try(:invalid?)
+ model = context[name] = super
+ raise NotFound if !optional && (!model || model.try(:empty?))
+
+ if model.try(:has_changes_to_save?) && (model.errors.present? || model.invalid?)
context[result_key].fail(invalid: true)
context.fail!
end
diff --git a/spec/lib/service/runner_spec.rb b/spec/lib/service/runner_spec.rb
index 4018e60072d..d1a97879906 100644
--- a/spec/lib/service/runner_spec.rb
+++ b/spec/lib/service/runner_spec.rb
@@ -87,6 +87,26 @@ RSpec.describe Service::Runner do
end
end
+ class FailureWithExistingModelErrorsService
+ include Service::Base
+
+ class Model
+ include ActiveModel::Validations
+
+ def has_changes_to_save?
+ true
+ end
+ end
+
+ model :fake_model, :fetch_fake_model
+
+ private
+
+ def fetch_fake_model
+ Model.new.tap { |model| model.errors.add(:base, "operation failed") }
+ end
+ end
+
class SuccessWithModelService
include Service::Base
@@ -471,6 +491,19 @@ RSpec.describe Service::Runner do
end
end
+ context "when the model already contains errors" do
+ let(:service) { FailureWithExistingModelErrorsService }
+ let(:actions) { <<-BLOCK }
+ proc do
+ on_model_errors(:fake_model) { |model| model.errors.full_messages }
+ end
+ BLOCK
+
+ it "preserves errors added by the model producer" do
+ expect(runner).to eq(["operation failed"])
+ end
+ end
+
context "when the service does not fail with a model containing errors" do
let(:service) { SuccessWithModelErrorsService }