我是 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