FactoryGirl.define do
  factory :stock_location, class: Spree::StockLocation do
    name 'NY Warehouse'
    address1 '1600 Pennsylvania Ave NW'
    city 'Washington'
    zipcode '20500'
    phone '(202) 456-1111'
    active true

    state  { |stock_location| stock_location.association(:state) }
    country  { |stock_location| stock_location.association(:country) }

    factory :stock_location_with_items do
      after(:create) do |stock_location, evaluator|
        # variant will add itself to all stock_locations in an after_create
        # creating a product will automatically create a master variant
        create(:product)
        create(:product)

        stock_location.stock_items.first.adjust_count_on_hand(10)
        stock_location.stock_items.second.adjust_count_on_hand(20)
      end
    end
  end
end

FactoryGirl.define do
  factory :stock_location, class: Spree::StockLocation do
    name 'NY Warehouse'
    address1 '1600 Pennsylvania Ave NW'
    city 'Washington'
    zipcode '20500'
    phone '(202) 456-1111'
    active true

    state  { |stock_location| stock_location.association(:state) }
    country  { |stock_location| stock_location.association(:country) }

    factory :stock_location_with_items do
      after(:create) do |stock_location, evaluator|
        # variant will add itself to all stock_locations in an after_create
        # creating a product will automatically create a master variant
        product_1 = create(:product)
        product_2 = create(:product)

        stock_location.stock_items.where(:variant_id => product_1.master.id).first.adjust_count_on_hand(10)
        stock_location.stock_items.where(:variant_id => product_2.master.id).first.adjust_count_on_hand(20)
      end
    end
  end
end

Adjust count on hand for stock items based on variant in stock location factory
Adjust count on hand for stock items based on variant in stock location factory

Given that stock_location.stock_items is unsorted, the behaviour of calling 'first' and 'last' is effectively random, leading it update the same stock item to have 30 items on hand.

By explicitly defining that we want THIS stock item to be updated with 10 and THIS one with 20, we don't run into that problem.

This is only a problem on MySQL when using InnoDB and on PostgreSQL always.
