我是Rspec和FactoryGirl的新手,用于测试ROR应用程序。我正在尝试测试一个模型类方法add_product(product_id)
并且当我在浏览器上尝试相同时它仍然失败但它仍然有效。这是模型的代码:
class Cart < ActiveRecord::Base
has_many :line_items, inverse_of: :cart
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(:product_id => product_id)
end
current_item
end
end
以下是购物车型号的失败规格:
describe Cart do
before(:each) do
@cart = FactoryGirl.create(:cart)
@product = FactoryGirl.create(:product)
@line_item = FactoryGirl.create(:line_item, product_id: @product.id, cart_id: @cart.id)
end
it 'increases the quantity of line_item when a similar product is added' do
lambda {@cart.add_product(@product.id)}.should change {@line_item.quantity}.by(1)
end
end
此操作失败,我从Rspec Failure/Error: lambda {@cart.add_product(@product.id)}.should change {@line_item.quantity}.by(1)
result should have been changed by 1, but was changed by 0
答案 0 :(得分:0)
数量正在更新,但您永远不会保留数据。因此,数据永远不会访问数据库,测试永远不会发生变化。你会遇到与.build相同的问题,直到你明确这么说才会持久存在。您可以通过执行此操作来更改此内容。
class Cart < ActiveRecord::Base
has_many :line_items, inverse_of: :cart
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
current_item.save
else
current_item = line_items.create(:product_id => product_id)
end
current_item
end
end