This is my product_spec.rb
describe Product do
before(:each) do
@sale = Sale.create
@product = @sale.products.build
@product.should be_valid
end
describe "price, quote, tax" do
before(:each) do
@product.price = 121
@product.price_before_discount = 200
@sale.tax_rate.should eq(21)
end
describe "integration with sale" do
it "should update sale upon saving" do
@sale.product_price.should eq(0.0)
@product.save.should be_true
@sale.reload
@sale.product_price.should eq(121)
end
it "should not affect the previous product_price" do
@product1 = @sale.products.create(price: 100)
@sale.reload
@sale.product_price.should eq(100)
@product2 = @sale.products.create(price: 100)
@sale.reload
@sale.product_price.should eq(200)
@product.save
@sale.reload
@sale.product_price.should eq(321)
end
end
end
end
This is product.rb
class Product < ActiveRecord::Base
after_create :update_sale_product_price
belongs_to :sale
validates_presence_of :sale
def update_sale_product_price
sale.reload
sale.product_price += price
sale.save
end
end
All the test are passing, but I would like to know if there is way to avoid reloading the the instance variable or how to deal with this kind of situations, is mock_model or stub_model or mocking methods the solution, because as you can see I need to reload even in the model.
Thanks