diff --git a/app/models/order_item.rb b/app/models/order_item.rb index b30b43b..ba5a4ae 100644 --- a/app/models/order_item.rb +++ b/app/models/order_item.rb @@ -13,7 +13,7 @@ class OrderItem < ActiveRecord::Base belongs_to :product validates :product, presence: true - validates :count, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } + validates :count, presence: true, numericality: { only_integer: true, greater_than: 0 } after_create :remove_from_stock diff --git a/spec/factories/order_items.rb b/spec/factories/order_items.rb index 70ce515..32acb2e 100644 --- a/spec/factories/order_items.rb +++ b/spec/factories/order_items.rb @@ -11,6 +11,7 @@ FactoryGirl.define do factory :order_item do order - product + association :product, factory: :product + count { 1 + rand(5) } end end diff --git a/spec/factories/orders.rb b/spec/factories/orders.rb index 33a0ccd..bcb779b 100644 --- a/spec/factories/orders.rb +++ b/spec/factories/orders.rb @@ -15,8 +15,11 @@ require 'faker' FactoryGirl.define do factory :order do user - before(:create) do |order| - order.order_items << build(:order_item, order: order) + transient do + products_count 1 + end + before(:create) do |order, evaluator| + order.order_items << create_list(:order_item, evaluator.products_count, order: order) end end end diff --git a/spec/factories/products.rb b/spec/factories/products.rb index e5eab1b..d971aa8 100644 --- a/spec/factories/products.rb +++ b/spec/factories/products.rb @@ -24,7 +24,7 @@ FactoryGirl.define do factory :product do name { Faker::Name.name } price_cents { rand 120 } - stock { rand 30 } + stock { 30 + rand(30) } calories { rand 20 } avatar { Identicon.data_url_for name } end diff --git a/spec/models/order_item_spec.rb b/spec/models/order_item_spec.rb index 563337f..dbc8605 100644 --- a/spec/models/order_item_spec.rb +++ b/spec/models/order_item_spec.rb @@ -24,6 +24,11 @@ describe OrderItem do @order_item.count = -5 expect(@order_item).to_not be_valid end + + it 'should not be 0' do + @order_item.count = 0 + expect(@order_item).to_not be_valid + end end end diff --git a/spec/models/order_spec.rb b/spec/models/order_spec.rb index 5373dae..6cf11c0 100644 --- a/spec/models/order_spec.rb +++ b/spec/models/order_spec.rb @@ -37,9 +37,19 @@ describe Order do end it 'should change the orders_count' do - expect(@user.reload.orders_count).to eq(1) - @order.cancel - expect(@user.reload.orders_count).to eq(0) + expect{@order.cancel}.to change{@user.reload.orders_count}.by(-1) + end + end + + describe 'price' do + it 'should be calculated from order_items' do + @order = build :order, products_count: 0 + sum = (create_list :product, 1 + rand(10)).map do |p| + create(:order_item, order: @order, product: p, count: 1 + rand(5)) do |oi| + @order.order_items << oi + end + end.map{ |oi| oi.count * oi.product.price_cents }.sum + expect(@order.price_cents).to eq(sum) end end end