Skip to content

Commit f3d92a4

Browse files
committed
Set required line item attributes earlier
This makes working with unpersisted line items easier because required attributes are set immediately. This change is in service of creating an in memory order updater.
1 parent e755cd5 commit f3d92a4

File tree

2 files changed

+14
-19
lines changed

2 files changed

+14
-19
lines changed

core/app/models/spree/line_item.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class LineItem < Spree::Base
2020
has_many :inventory_units, inverse_of: :line_item
2121

2222
before_validation :normalize_quantity
23-
before_validation :set_required_attributes
23+
after_initialize :set_required_attributes
2424

2525
validates :variant, presence: true
2626
validates :quantity, numericality: {
@@ -157,6 +157,7 @@ def normalize_quantity
157157
# Sets tax category, price-related attributes from
158158
# its variant if they are nil and a variant is present.
159159
def set_required_attributes
160+
return if persisted?
160161
return unless variant
161162
self.tax_category ||= variant.tax_category
162163
set_pricing_attributes

core/spec/models/spree/line_item_spec.rb

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -39,31 +39,25 @@
3939
end
4040
end
4141

42-
describe 'line item creation' do
42+
describe '.new' do
4343
let(:variant) { create :variant }
4444

4545
subject(:line_item) { Spree::LineItem.new(variant:, order:) }
4646

47-
# Tests for https://github.com/spree/spree/issues/3391
48-
context 'before validation' do
49-
before { line_item.valid? }
50-
51-
it 'copies the variants price' do
52-
expect(line_item.price).to eq(variant.price)
53-
end
47+
it 'copies the variants price' do
48+
expect(line_item.price).to eq(variant.price)
49+
end
5450

55-
it 'copies the variants cost_price' do
56-
expect(line_item.cost_price).to eq(variant.cost_price)
57-
end
51+
it 'copies the variants cost_price' do
52+
expect(line_item.cost_price).to eq(variant.cost_price)
53+
end
5854

59-
it "copies the order's currency" do
60-
expect(line_item.currency).to eq(order.currency)
61-
end
55+
it "copies the order's currency" do
56+
expect(line_item.currency).to eq(order.currency)
57+
end
6258

63-
# Test for https://github.com/spree/spree/issues/3481
64-
it 'copies the variants tax category' do
65-
expect(line_item.tax_category).to eq(line_item.variant.tax_category)
66-
end
59+
it 'copies the variants tax category' do
60+
expect(line_item.tax_category).to eq(line_item.variant.tax_category)
6761
end
6862
end
6963

0 commit comments

Comments
 (0)