diff --git a/lib/open_food_network/variant_stock.rb b/lib/open_food_network/variant_stock.rb index 0b2773542d..98bde544f7 100644 --- a/lib/open_food_network/variant_stock.rb +++ b/lib/open_food_network/variant_stock.rb @@ -98,6 +98,7 @@ module OpenFoodNetwork warn_deprecation(__method__, 'Spree::Config[:track_inventory_levels]') raise_error_if_no_stock_item_available + raise_error_if_multiple_stock_items # There should be only one at the default stock location. # @@ -125,6 +126,11 @@ module OpenFoodNetwork raise message if stock_items.empty? end + def raise_error_if_multiple_stock_items + message = 'A variant cannot have more than a stock item.' + raise message if stock_items.size > 1 + end + # Backwards compatible setting of stock levels in Spree 2.0. # It would be better to use `Spree::StockItem.adjust_count_on_hand` which # takes a value to add to the current stock level and uses proper locking. diff --git a/spec/lib/open_food_network/variant_stock_spec.rb b/spec/lib/open_food_network/variant_stock_spec.rb index 1c3efb88ca..b0818f6690 100644 --- a/spec/lib/open_food_network/variant_stock_spec.rb +++ b/spec/lib/open_food_network/variant_stock_spec.rb @@ -129,6 +129,21 @@ describe OpenFoodNetwork::VariantStock do end describe '#on_demand=' do + context 'when the variant has multiple stock items' do + let(:variant) { create(:variant) } + + before do + # Spree creates a stock_item for each variant when creating a stock + # location by means of #propagate_variant + create(:stock_location, name: 'location') + create(:stock_location, name: 'another location') + end + + it 'raises' do + expect { variant.on_demand = true }.to raise_error(StandardError) + end + end + context 'when the variant has a stock item' do let(:variant) { create(:variant, on_demand: true) }