@@ -550,6 +550,8 @@ class Extension < Spree::Base
550550 end
551551
552552 context '#total_on_hand' do
553+ let ( :product ) { create :product }
554+
553555 it 'should be infinite if track_inventory_levels is false' do
554556 stub_spree_preferences ( track_inventory_levels : false )
555557 expect ( build ( :product , variants_including_master : [ build ( :master_variant ) ] ) . total_on_hand ) . to eql ( Float ::INFINITY )
@@ -561,17 +563,30 @@ class Extension < Spree::Base
561563 end
562564
563565 it 'should return sum of stock items count_on_hand' do
564- product = create ( :product )
565566 product . stock_items . first . set_count_on_hand 5
566567 product . variants_including_master . reload # force load association
567568 expect ( product . total_on_hand ) . to eql ( 5 )
568569 end
569570
570571 it 'should return sum of stock items count_on_hand when variants_including_master is not loaded' do
571- product = create ( :product )
572572 product . stock_items . first . set_count_on_hand 5
573573 expect ( product . reload . total_on_hand ) . to eql ( 5 )
574574 end
575+
576+ context 'when the stock items are loaded' do
577+ it 'returns the loaded count_on_hand instead of doing SUM(count_on_hand)' do
578+ product . stock_items . first . set_count_on_hand ( 5 )
579+
580+ product = described_class . includes ( :stock_items ) . find ( product . id )
581+
582+ # Set the count on hand to a different number to highlight we loaded and
583+ # must be done from the class level so that we don't update the instance
584+ # product has loaded
585+ Spree ::StockItem . find ( product . stock_items . first . id ) . set_count_on_hand ( 7 )
586+
587+ expect ( product . total_on_hand ) . to eql 5
588+ end
589+ end
575590 end
576591
577592 # Regression spec for https://github.com/spree/spree/issues/5588
0 commit comments