From 9ebe112bcc754136211068b9e1f9d0cb02842f2b Mon Sep 17 00:00:00 2001 From: Pau Perez Date: Fri, 11 Jan 2019 15:52:09 +0100 Subject: [PATCH] Abstract OFN's default stock location into a class --- app/services/default_stock_location.rb | 15 +++++++++ spec/factories.rb | 4 ++- spec/services/default_stock_location_spec.rb | 32 ++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 app/services/default_stock_location.rb create mode 100644 spec/services/default_stock_location_spec.rb diff --git a/app/services/default_stock_location.rb b/app/services/default_stock_location.rb new file mode 100644 index 0000000000..e2df33cb71 --- /dev/null +++ b/app/services/default_stock_location.rb @@ -0,0 +1,15 @@ +# Encapsulates the concept of default stock location that OFN has, as explained +# in https://github.com/openfoodfoundation/openfoodnetwork/wiki/Spree-Upgrade%3A-Stock-locations +class DefaultStockLocation + NAME = 'OFN default'.freeze + + def self.create! + country = Spree::Country.find_by_iso(ENV['DEFAULT_COUNTRY_CODE']) + state = country.states.first + Spree::StockLocation.create!(name: NAME, country_id: country.id, state_id: state.id) + end + + def self.destroy_all + Spree::StockLocation.where(name: NAME).destroy_all + end +end diff --git a/spec/factories.rb b/spec/factories.rb index 58273f7cb5..582dd4d98b 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -656,8 +656,10 @@ end FactoryBot.modify do factory :stock_location, class: Spree::StockLocation do + name { 'default' } + # keeps the test stock_location unique - initialize_with { Spree::StockLocation.find_or_create_by_name(name)} + initialize_with { DefaultStockLocation.find_or_create } end factory :shipment, class: Spree::Shipment do diff --git a/spec/services/default_stock_location_spec.rb b/spec/services/default_stock_location_spec.rb new file mode 100644 index 0000000000..b2b9691267 --- /dev/null +++ b/spec/services/default_stock_location_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' + +describe DefaultStockLocation do + describe '.create!' do + it "names the location 'OFN default'" do + stock_location = described_class.create! + expect(stock_location.name).to eq('OFN default') + end + + it 'sets the location in the default country' do + default_country = Spree::Country.find_by_iso(ENV['DEFAULT_COUNTRY_CODE']) + stock_location = described_class.create! + expect(stock_location.country).to eq(default_country) + end + + it 'sets the first state in the country' do + default_country = Spree::Country.find_by_iso(ENV['DEFAULT_COUNTRY_CODE']) + stock_location = described_class.create! + expect(stock_location.state).to eq(default_country.states.first) + end + end + + describe '.destroy_all' do + it "removes all stock locations named 'OFN default'" do + create(:stock_location, name: 'OFN default') + create(:stock_location, name: 'OFN default') + + expect { described_class.destroy_all } + .to change { Spree::StockLocation.count }.from(2).to(0) + end + end +end