Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Address review feedback on validation workflows

Damian Legawiecf91093d6fdce
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdx
index 62445481b9..d3ceeac5f9 100644
--- a/docs/developer/customization/workflows.mdx
+++ b/docs/developer/customization/workflows.mdx
@@ -202,9 +202,10 @@ The caller receives a normal failure result — no exception reaches your
controller:
```ruby
-result = Spree.cart_add_item_workflow.call(cart: cart, variant: variant)
+result = Spree.return_create_workflow.call(order: order, items: items)
result.success? # => false
-result.error.value # => "You can order at most 10 of this item."
+result.error.to_s # => "This order is outside the 30-day return window."
+result.error.value # => ActiveModel::Errors — the rejection, field by field
```
<Warning>
@@ -252,7 +253,7 @@ is reported through `Rails.error` so it's visible rather than mysterious.
|---|---|---|---|
| `carts.add_item` | `validate` | validate | Before the line item is built |
| `carts.add_item` | `after_item_added` | lifecycle | After the item is saved and totals recalculated (in transaction) |
-| `carts.upsert_items` | `validate` | validate | Once per item, before anything is written — quantity edits, removals and bulk payloads |
+| `carts.upsert_items` | `validate` | validate | Once per item, immediately before that item is applied — quantity edits, removals and bulk payloads. Earlier items in the batch may already be written |
| `carts.upsert_items` | `after_items_upserted` | lifecycle | After the batch is applied and the cart recalculated once (in transaction) |
| `carts.complete` | `validate` | validate | After checkout requirements pass, before the order is created |
| `carts.complete` | `before_finalize` | lifecycle | After payment, before the order is placed |
diff --git a/docs/docs.json b/docs/docs.json
index e0abceb82f..b91f6dc932 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -333,7 +333,6 @@
"developer/customization/checkout",
"developer/customization/permissions",
"developer/customization/workflows",
- "developer/customization/validations",
"developer/customization/dependencies",
"developer/customization/decorators",
"developer/customization/model-preferences",
diff --git a/docs/plans/6.0-extendable-validations.md b/docs/plans/6.0-extendable-validations.md
index f539704a6c..d45a443498 100644
--- a/docs/plans/6.0-extendable-validations.md
+++ b/docs/plans/6.0-extendable-validations.md
@@ -153,12 +153,11 @@ class Spree::Carts::UpsertItems < Spree::Workflow
def perform(cart:, items:)
super
- step :resolve_items # one query for all variants, currency check
- each_item { run_hooks :validate } # cart/variant/quantity readers per item
+ step :resolve_items # one query for all variants
ApplicationRecord.transaction do
- step :apply_items # shared collaborators with AddItem:
- # find/build line item, save, price capture,
- # tax estimate for new items
+ step :apply_items # per item: run_hooks :validate, then apply
+ # (find/build line item, save, price capture,
+ # tax estimate for new items)
step :handle_stock_reservations if cart.in_checkout?
step :recalculate, with: -> { Spree.cart_recalculate_workflow }
run_hooks :after_items_upserted
@@ -175,14 +174,21 @@ written for `carts.add_item.validate` therefore works unchanged when also
registered on `carts.upsert_items.validate`.
Semantics: upsert **sets** quantity (unlike `AddItem`, which increments), and
-quantity `0` removes the line item. Per-item rejection semantics differ from
-every other workflow: the batch loop catches a `reject!` raised during an
-item's `validate` dispatch, skips that item, and records a warning
-(`item_index`, `code`, `message` — derived from the item's `errors` object);
-the remaining items proceed and the cart recalculates over what actually
-applied. The workflow returns the cart plus the collected warnings, and the
-Store API renders them as a top-level `warnings` array beside the cart
-payload (SDK types updated to match).
+quantity `0` removes the line item. **Validation is per item, not a batch
+pre-pass:** each item is validated immediately before it is applied, so an
+item's handler runs after earlier items in the same batch have already been
+written inside the transaction. A handler must therefore judge the item it is
+given rather than assume nothing has happened yet.
+
+Per-item rejection semantics differ from every other workflow: the batch loop
+catches a `reject!` raised during an item's `validate` dispatch, skips that
+item, and records a warning (`item_index`, `code`, `message` — derived from
+the item's `errors` object). A line that fails to **save** (stock
+availability, say) is treated the same way rather than aborting the batch.
+The remaining items proceed and the cart recalculates over what actually
+applied. Warnings are written to the cart's own `warnings` attribute, so
+clients read them at `cart.warnings` in the ordinary cart payload — not as a
+separate top-level key.
Call sites routed through it: `Carts::Create` / `Carts::Update` (`items:`
payloads), the Store API bulk item endpoints, PATCH quantity, and DELETE item.
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
index 0de99f6c63..f39f21caec 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb
@@ -34,6 +34,18 @@ module Spree
@line_item = @cart.line_items.find_by_prefix_id!(params[:id])
if permitted_params[:quantity].present?
+ # Zero and negatives remove the row in the upsert vocabulary,
+ # but this endpoint documents `quantity >= 1` and DELETE is
+ # how a client removes an item. Deleting on a PATCH the
+ # schema forbids would be a surprising 200.
+ if permitted_params[:quantity].to_i < 1
+ return render_error(
+ code: ERROR_CODES[:invalid_quantity],
+ message: Spree.t('cart_line_item.quantity_must_be_positive'),
+ status: :unprocessable_content
+ )
+ end
+
result = Spree.cart_upsert_items_workflow.call(
cart: @cart,
items: [{
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
index de2e162737..b85490302f 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
@@ -132,6 +132,19 @@ RSpec.describe Spree::Api::V3::Store::Carts::ItemsController, type: :controller
expect(response).to have_http_status(:not_found)
end
+
+ # Zero removes the row in the upsert vocabulary, but this endpoint
+ # documents quantity >= 1 and DELETE is how a client removes an item.
+ [0, -1].each do |quantity|
+ it "rejects a quantity of #{quantity} instead of deleting the item" do
+ expect do
+ patch :update, params: { cart_id: order.prefixed_id, id: line_item.prefixed_id, quantity: quantity }
+ end.not_to change(Spree::LineItem, :count)
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_quantity')
+ end
+ end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
index f4dabb6ccf..d9c3e604fb 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
@@ -327,6 +327,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
delete 'Delete a product' do
tags 'Products'
+ produces 'application/json'
security [api_key: [], bearer_auth: []]
description 'Soft-deletes a product.'
admin_scope :write, :products
diff --git a/spree/core/app/jobs/spree/variants/remove_line_item_job.rb b/spree/core/app/jobs/spree/variants/remove_line_item_job.rb
index dbe13527c4..b7b8e4417b 100644
--- a/spree/core/app/jobs/spree/variants/remove_line_item_job.rb
+++ b/spree/core/app/jobs/spree/variants/remove_line_item_job.rb
@@ -4,11 +4,28 @@ module Spree
queue_as Spree.queues.variants
def perform(line_item:)
- Spree.cart_upsert_items_workflow.call(
+ workflow = Spree.cart_upsert_items_workflow.new
+ result = workflow.call(
cart: line_item.owner,
items: [{ variant_id: line_item.variant_id, quantity: 0 }]
)
+
+ # The cart-side contract turns a vetoed removal into a warning and
+ # still succeeds, so the job has to look at the warnings to know the
+ # line survived — otherwise a discontinued variant silently stays in
+ # the cart with nothing to show for it.
+ rejection = workflow.warnings.first
+ return if result.success? && rejection.nil?
+
+ Rails.error.report(
+ RemovalRejected.new(rejection&.message || result.error.to_s),
+ context: { line_item_id: line_item.id, variant_id: line_item.variant_id },
+ source: 'spree.variants.remove_line_item',
+ handled: true
+ )
end
+
+ class RemovalRejected < StandardError; end
end
end
end
diff --git a/spree/core/app/services/spree/carts/remove_line_item.rb b/spree/core/app/services/spree/carts/remove_line_item.rb
index 6672d98c44..c8eb2a5386 100644
--- a/spree/core/app/services/spree/carts/remove_line_item.rb
+++ b/spree/core/app/services/spree/carts/remove_line_item.rb
@@ -7,19 +7,32 @@ module Spree
class RemoveLineItem
prepend Spree::ServiceModule::Base
+ # @param options [Hash] accepted for signature compatibility and ignored —
+ # the upsert path identifies the row by variant, not by line-item options.
def call(cart: nil, order: nil, line_item: nil, options: nil)
Spree::Deprecation.warn(
'Spree::Carts::RemoveLineItem is deprecated and will be removed in Spree 6.1. ' \
- 'Use Spree::Carts::UpsertItems with quantity: 0 instead.'
+ 'Use Spree::Carts::UpsertItems with quantity: 0 instead. Note it removes the ' \
+ 'cart\'s line item for the variant, which is this one unless the cart holds ' \
+ 'several rows of the same variant.'
)
cart ||= order
- result = Spree.cart_upsert_items_workflow.call(
+ workflow = Spree.cart_upsert_items_workflow.new
+ result = workflow.call(
cart: cart,
items: [{ variant_id: line_item.variant_id, quantity: 0 }]
)
- result.success? ? success(line_item) : failure(line_item, result.error)
+ return failure(line_item, result.error) if result.failure?
+
+ # A :validate handler may have vetoed the removal; on the cart side
+ # that is a warning rather than a failed result, but this service's
+ # callers expect a failure.
+ rejection = workflow.warnings.first
+ return failure(line_item, rejection.message) if rejection
+
+ success(line_item)
end
end
end
diff --git a/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb b/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb
index aa6b291f80..d4d3d4ec4e 100644
--- a/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb
+++ b/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb
@@ -16,13 +16,21 @@ module Spree
line_items = cart.line_items.includes(variant: [:product, :stock_locations, { stock_items: [:stock_location, :active_stock_reservations] }])
ActiveRecord::Base.transaction do
+ # The predicates record a message per candidate as they run, so the
+ # messages exist before the removal is attempted.
removals = line_items.reject { |line_item| valid_status?(line_item) && stock_available?(line_item) }
if removals.any?
- Spree.cart_upsert_items_workflow.call(
+ workflow = Spree.cart_upsert_items_workflow.new
+ workflow.call(
cart: cart,
items: removals.map { |line_item| { variant_id: line_item.variant_id, quantity: 0 } }
)
+
+ # A :validate handler can veto a removal, leaving the line in the
+ # cart. Telling the customer it was removed would be a lie, so
+ # retract the message for anything that survived.
+ discard_messages_for(workflow.warnings)
end
end
@@ -35,6 +43,19 @@ module Spree
private
+ # @param item_warnings [Array<Spree::Carts::ItemWarning>] items the upsert
+ # did not remove
+ def discard_messages_for(item_warnings)
+ return if item_warnings.empty?
+
+ surviving_variant_ids = item_warnings.filter_map { |warning| warning.variant&.prefixed_id }
+ return if surviving_variant_ids.empty?
+
+ retracted = @warnings.select { |warning| surviving_variant_ids.include?(warning[:variant_id]) }
+ @messages -= retracted.map { |warning| warning[:message] }
+ @warnings -= retracted
+ end
+
def valid_status?(line_item)
product = line_item.product
if !product.active? || product.deleted? || product.discontinued? || line_item.variant.discontinued?
diff --git a/spree/core/app/services/spree/carts/set_quantity.rb b/spree/core/app/services/spree/carts/set_quantity.rb
index f7e6b8121f..34bd5aa24a 100644
--- a/spree/core/app/services/spree/carts/set_quantity.rb
+++ b/spree/core/app/services/spree/carts/set_quantity.rb
@@ -14,12 +14,22 @@ module Spree
)
cart ||= order
- result = Spree.cart_upsert_items_workflow.call(
+ workflow = Spree.cart_upsert_items_workflow.new
+ result = workflow.call(
cart: cart,
items: [{ variant_id: line_item.variant_id, quantity: quantity }]
)
- result.success? ? success(line_item.reload) : failure(line_item, result.error)
+ return failure(line_item, result.error) if result.failure?
+
+ # The workflow succeeds on the cart side even when a :validate handler
+ # skipped this item — that is the batch contract. This service's
+ # callers predate it and expect a failure, so translate the warning.
+ rejection = workflow.warnings.first
+ return failure(line_item, rejection.message) if rejection
+
+ # Zero removed the row, so there is nothing to reload.
+ line_item.destroyed? || quantity.to_i <= 0 ? success(line_item) : success(line_item.reload)
end
end
end
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index 037fd2ebd3..eda4acf332 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -121,7 +121,17 @@ module Spree
Spree.product_update_workflow.call(product: product)
end
- raise ActiveRecord::RecordInvalid, product if result.failure?
+ if result.failure?
+ # A hook rejection carries its own errors, not the product's, so
+ # copy them across — otherwise the failed row records an empty
+ # validation_errors and the merchant sees no reason.
+ rejection = result.error&.value
+ if rejection.is_a?(ActiveModel::Errors) && product.errors.empty?
+ rejection.each { |error| product.errors.add(error.attribute, error.message) }
+ end
+
+ raise ActiveRecord::RecordInvalid, product
+ end
product
end
diff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rb
index e44b64c897..cdaf14f902 100644
--- a/spree/core/app/workflows/spree/carts/upsert_items.rb
+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb
@@ -112,7 +112,7 @@ module Spree
next
end
- apply_item(item, line_item)
+ apply_item(item, line_item, index)
end
end
@@ -146,7 +146,7 @@ module Spree
@metadata = item&.metadata || {}
end
- def apply_item(item, line_item)
+ def apply_item(item, line_item, index)
if line_item
line_item.quantity = item.quantity
line_item.metadata = line_item.metadata.merge(item.metadata) if item.metadata.present?
@@ -160,7 +160,18 @@ module Spree
end
created = line_item.new_record?
- failure(line_item) unless line_item.save
+
+ # A line that won't save — most often the stock availability
+ # validator — is this item's problem, not the batch's. Failing here
+ # would roll back every other line, which is exactly what a customer
+ # restoring a saved cart must not lose.
+ unless line_item.save
+ failure(line_item) unless partial_success?
+
+ warn(index, item, line_item.errors.details.values.flatten.first&.dig(:error) || :invalid,
+ line_item.errors.full_messages.to_sentence)
+ return
+ end
line_item.reload.recalculate_price
::Spree.tax_provider.estimate(line_item.owner, [line_item]) if created
diff --git a/spree/core/app/workflows/spree/products/create.rb b/spree/core/app/workflows/spree/products/create.rb
index 0e85e2773c..20471fc22e 100644
--- a/spree/core/app/workflows/spree/products/create.rb
+++ b/spree/core/app/workflows/spree/products/create.rb
@@ -46,6 +46,11 @@ module Spree
def build_product
@product = record || store.products.new
+ # A supplied record must belong to the store the caller named — a
+ # product resolved outside that scope would otherwise be persisted
+ # against the wrong tenant, and every :validate handler reading
+ # `store` would be told the wrong thing.
+ @product.store = store
@product.assign_attributes(attributes) if attributes.present?
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 0eeec2e5b3..8d656796df 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -678,6 +678,7 @@ en:
cart_already_updated: The cart has already been updated.
cart_line_item:
currency_unavailable: "%{li_name} is not available in %{currency}"
+ quantity_must_be_positive: Quantity must be at least 1. Use DELETE to remove the item.
delivery_unavailable: "%{li_name} cannot be delivered to the selected address"
discontinued: "%{li_name} was removed because it was discontinued"
out_of_stock: "%{li_name} was removed because it was sold out"
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 4beae6c363..578ef2f55f 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -21,6 +21,12 @@ module Spree
cart_recalculate_totals_workflow: 'Spree::Carts::RecalculateTotals',
order_recalculate_totals_workflow: 'Spree::Orders::RecalculateTotals',
cart_remove_item_service: 'Spree::Carts::RemoveItem',
+ # Deprecated shims, not the workflow: they still speak the old
+ # line_item:/quantity: vocabulary and delegate to
+ # cart_upsert_items_workflow internally. Pointing these at the
+ # workflow would ArgumentError on every legacy caller.
+ cart_remove_line_item_service: 'Spree::Carts::RemoveLineItem',
+ cart_set_item_quantity_service: 'Spree::Carts::SetQuantity',
# draft orders (admin item editing) — cart twins split so the two
# sides can diverge; see Spree::Orders::AddItem
@@ -149,8 +155,6 @@ module Spree
cart_merge_strategy: :cart_merge_workflow,
carts_complete_service: :carts_complete_workflow,
carts_upsert_items_service: :cart_upsert_items_workflow,
- cart_set_item_quantity_service: :cart_upsert_items_workflow,
- cart_remove_line_item_service: :cart_upsert_items_workflow,
payments_handle_webhook_service: :payments_handle_webhook_workflow,
fulfillment_create_service: :fulfillment_create_workflow,
order_cancel_service: :order_cancel_workflow,
diff --git a/spree/core/spec/services/spree/carts/set_quantity_spec.rb b/spree/core/spec/services/spree/carts/set_quantity_spec.rb
index 64e9f77839..46f97ea5a4 100644
--- a/spree/core/spec/services/spree/carts/set_quantity_spec.rb
+++ b/spree/core/spec/services/spree/carts/set_quantity_spec.rb
@@ -90,5 +90,36 @@ module Spree
end
end
end
+
+ # The workflow this shim delegates to removes the row on a zero quantity,
+ # so a naive `line_item.reload` here would raise instead of returning a
+ # result — the contract legacy callers were written against.
+ describe 'a zero quantity' do
+ it 'removes the line item and still returns a result' do
+ line_item # the shim needs it to exist before the baseline is taken
+ result = nil
+
+ expect { result = subject.call(cart: cart, line_item: line_item, quantity: 0) }.
+ to change { cart.reload.line_items.count }.by(-1)
+
+ expect(result).to be_success
+ end
+ end
+
+ # The cart-side workflow turns a vetoed item into a warning and succeeds.
+ # This service's callers predate that, so it has to report the failure.
+ describe 'a rejected quantity change' do
+ after { Spree.hooks.clear! }
+
+ it 'returns a failure' do
+ Spree.hooks.register('carts.upsert_items.validate') { |flow| flow.reject!('over the limit') }
+
+ result = subject.call(cart: cart, line_item: line_item, quantity: 3)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('over the limit')
+ end
+ end
+
end
end
diff --git a/spree/core/spec/workflows/spree/carts/upsert_items_spec.rb b/spree/core/spec/workflows/spree/carts/upsert_items_spec.rb
index ea9a8c5408..35548ab528 100644
--- a/spree/core/spec/workflows/spree/carts/upsert_items_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/upsert_items_spec.rb
@@ -316,6 +316,28 @@ module Spree
end
end
+ # A line that cannot be saved is that line's problem. Failing the batch
+ # would throw away every other item the customer still wants.
+ describe 'a line item that will not save' do
+ let(:items) do
+ [
+ { variant_id: variant.prefixed_id, quantity: 1 },
+ { variant_id: variant2.prefixed_id, quantity: 999 }
+ ]
+ end
+
+ before { variant2.stock_items.first.update!(count_on_hand: 1, backorderable: false) }
+
+ it 'warns and keeps the rest of the batch' do
+ workflow = described_class.new
+ result = workflow.call(cart: cart, items: items)
+
+ expect(result).to be_success
+ expect(cart.reload.items.map(&:variant)).to eq([variant])
+ expect(workflow.warnings.sole.item_index).to eq(1)
+ end
+ end
+
describe 'removals' do
let!(:line_item) { create(:line_item, cart: cart, order: nil, variant: variant, quantity: 2) }
diff --git a/spree/core/spec/workflows/spree/products/lifecycle_spec.rb b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
index 8375c8fa0a..763ac1a3a5 100644
--- a/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/products/lifecycle_spec.rb
@@ -1,148 +1,150 @@
require 'spec_helper'
-RSpec.describe 'product workflows' do
- let(:store) { @default_store }
+module Spree
+ RSpec.describe 'product workflows' do
+ let(:store) { @default_store }
- after { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
- describe Spree::Products::Create do
- it 'creates the product' do
- result = described_class.call(store: store, attributes: { name: 'Chair' })
+ describe Products::Create do
+ it 'creates the product' do
+ result = described_class.call(store: store, attributes: { name: 'Chair' })
- expect(result).to be_success
- expect(result.value).to be_persisted
- expect(result.value.name).to eq('Chair')
- expect(result.value.store).to eq(store)
- end
-
- it 'lets a validate handler reject the product before it is written' do
- Spree.hooks.register('products.create.validate') do |flow|
- flow.errors.add(:name, :reserved_word, message: 'may not contain "sample"')
- flow.reject! if flow.product.name.to_s.include?('sample')
+ expect(result).to be_success
+ expect(result.value).to be_persisted
+ expect(result.value.name).to eq('Chair')
+ expect(result.value.store).to eq(store)
end
- result = described_class.call(store: store, attributes: { name: 'a sample chair' })
+ it 'lets a validate handler reject the product before it is written' do
+ Spree.hooks.register('products.create.validate') do |flow|
+ flow.errors.add(:name, :reserved_word, message: 'may not contain "sample"')
+ flow.reject! if flow.product.name.to_s.include?('sample')
+ end
- expect(result).to be_failure
- expect(result.error.to_s).to include('may not contain')
- expect(Spree::Product.find_by(name: 'a sample chair')).to be_nil
- end
+ result = described_class.call(store: store, attributes: { name: 'a sample chair' })
- it 'fires after_create with the saved product' do
- seen = nil
- Spree.hooks.register('products.create.after_create') { |flow| seen = flow.product }
+ expect(result).to be_failure
+ expect(result.error.to_s).to include('may not contain')
+ expect(Product.find_by(name: 'a sample chair')).to be_nil
+ end
- described_class.call(store: store, attributes: { name: 'Desk' })
+ it 'fires after_create with the saved product' do
+ seen = nil
+ Spree.hooks.register('products.create.after_create') { |flow| seen = flow.product }
- expect(seen).to be_persisted
- expect(seen.name).to eq('Desk')
- end
+ described_class.call(store: store, attributes: { name: 'Desk' })
- it 'returns a failure when the product is invalid' do
- result = described_class.call(store: store, attributes: { name: '' })
+ expect(seen).to be_persisted
+ expect(seen.name).to eq('Desk')
+ end
- expect(result).to be_failure
- expect(result.error.to_s).to include("Name can't be blank")
- end
+ it 'returns a failure when the product is invalid' do
+ result = described_class.call(store: store, attributes: { name: '' })
- # Nested data is written by the model's after_create callbacks, so a
- # rejection before the insert leaves no half-built product behind.
- it 'writes no nested data when a handler rejects' do
- Spree.hooks.register('products.create.validate') { |flow| flow.reject!('not allowed') }
+ expect(result).to be_failure
+ expect(result.error.to_s).to include("Name can't be blank")
+ end
+
+ # Nested data is written by the model's after_create callbacks, so a
+ # rejection before the insert leaves no half-built product behind.
+ it 'writes no nested data when a handler rejects' do
+ Spree.hooks.register('products.create.validate') { |flow| flow.reject!('not allowed') }
+
+ result = nil
+ expect do
+ result = described_class.call(
+ store: store,
+ attributes: { name: 'Rejected', variants: [{ sku: 'REJ-1' }] }
+ )
+ end.not_to change(Variant, :count)
+
+ expect(result).to be_failure
+ expect(Product.find_by(name: 'Rejected')).to be_nil
+ end
- result = nil
- expect do
+ # The setters live on the model, so a workflow create gets them too.
+ it 'applies nested variants through the model setters' do
result = described_class.call(
store: store,
- attributes: { name: 'Rejected', variants: [{ sku: 'REJ-1' }] }
+ attributes: { name: 'With variants', variants: [{ sku: 'WV-1' }] }
)
- end.not_to change(Spree::Variant, :count)
- expect(result).to be_failure
- expect(Spree::Product.find_by(name: 'Rejected')).to be_nil
- end
-
- # The setters live on the model, so a workflow create gets them too.
- it 'applies nested variants through the model setters' do
- result = described_class.call(
- store: store,
- attributes: { name: 'With variants', variants: [{ sku: 'WV-1' }] }
- )
-
- expect(result).to be_success
- expect(result.value.variants.map(&:sku)).to include('WV-1')
- end
+ expect(result).to be_success
+ expect(result.value.variants.map(&:sku)).to include('WV-1')
+ end
- # The CSV importer assigns attributes across several steps and hands over
- # the record rather than a hash.
- it 'accepts an already-built product' do
- product = store.products.new(name: 'Prebuilt')
+ # The CSV importer assigns attributes across several steps and hands over
+ # the record rather than a hash.
+ it 'accepts an already-built product' do
+ product = store.products.new(name: 'Prebuilt')
- result = described_class.call(store: store, record: product)
+ result = described_class.call(store: store, record: product)
- expect(result).to be_success
- expect(product.reload).to be_persisted
+ expect(result).to be_success
+ expect(product.reload).to be_persisted
+ end
end
- end
- describe Spree::Products::Update do
- let(:product) { create(:product, store: store, name: 'Original') }
+ describe Products::Update do
+ let(:product) { create(:product, store: store, name: 'Original') }
- it 'applies the attributes' do
- result = described_class.call(product: product, attributes: { name: 'Renamed' })
+ it 'applies the attributes' do
+ result = described_class.call(product: product, attributes: { name: 'Renamed' })
- expect(result).to be_success
- expect(product.reload.name).to eq('Renamed')
- end
+ expect(result).to be_success
+ expect(product.reload.name).to eq('Renamed')
+ end
- # Reading `changes` in validate is what makes "the price may not drop
- # below cost" expressible without a model validation.
- it 'exposes the pending edit to a validate handler' do
- pending_change = nil
- Spree.hooks.register('products.update.validate') { |flow| pending_change = flow.product.changes['name'] }
+ # Reading `changes` in validate is what makes "the price may not drop
+ # below cost" expressible without a model validation.
+ it 'exposes the pending edit to a validate handler' do
+ pending_change = nil
+ Spree.hooks.register('products.update.validate') { |flow| pending_change = flow.product.changes['name'] }
- described_class.call(product: product, attributes: { name: 'Renamed' })
+ described_class.call(product: product, attributes: { name: 'Renamed' })
- expect(pending_change).to eq(%w[Original Renamed])
- end
+ expect(pending_change).to eq(%w[Original Renamed])
+ end
- it 'leaves the record untouched when a handler rejects' do
- Spree.hooks.register('products.update.validate') { |flow| flow.reject!('locked for editing') }
+ it 'leaves the record untouched when a handler rejects' do
+ Spree.hooks.register('products.update.validate') { |flow| flow.reject!('locked for editing') }
- result = described_class.call(product: product, attributes: { name: 'Renamed' })
+ result = described_class.call(product: product, attributes: { name: 'Renamed' })
- expect(result).to be_failure
- expect(product.reload.name).to eq('Original')
+ expect(result).to be_failure
+ expect(product.reload.name).to eq('Original')
+ end
end
- end
- describe Spree::Products::Destroy do
- let!(:product) { create(:product, store: store) }
+ describe Products::Destroy do
+ let!(:product) { create(:product, store: store) }
- it 'soft-deletes the product' do
- result = described_class.call(product: product)
+ it 'soft-deletes the product' do
+ result = described_class.call(product: product)
- expect(result).to be_success
- expect(product.reload.deleted_at).to be_present
- end
+ expect(result).to be_success
+ expect(product.reload.deleted_at).to be_present
+ end
- it 'lets a handler refuse the deletion' do
- Spree.hooks.register('products.destroy.validate') { |flow| flow.reject!('still under contract') }
+ it 'lets a handler refuse the deletion' do
+ Spree.hooks.register('products.destroy.validate') { |flow| flow.reject!('still under contract') }
- result = described_class.call(product: product)
+ result = described_class.call(product: product)
- expect(result).to be_failure
- expect(result.error.to_s).to eq('still under contract')
- expect(product.reload.deleted_at).to be_nil
- end
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('still under contract')
+ expect(product.reload.deleted_at).to be_nil
+ end
- it 'fires after_destroy for host cleanup' do
- fired = false
- Spree.hooks.register('products.destroy.after_destroy') { fired = true }
+ it 'fires after_destroy for host cleanup' do
+ fired = false
+ Spree.hooks.register('products.destroy.after_destroy') { fired = true }
- described_class.call(product: product)
+ described_class.call(product: product)
- expect(fired).to be(true)
+ expect(fired).to be(true)
+ end
end
end
end