Add order price test

This commit is contained in:
benji 2015-09-04 16:47:49 +02:00
parent 43fd368bc7
commit b1dbe76746
6 changed files with 27 additions and 8 deletions

View file

@ -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

View file

@ -11,6 +11,7 @@
FactoryGirl.define do
factory :order_item do
order
product
association :product, factory: :product
count { 1 + rand(5) }
end
end

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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