[英]Testing a class method for a model using Rspec and FactoryGirl in Rails
I am new to Rspec and FactoryGirl for testing ROR applications. 我是Rspec和FactoryGirl的测试ROR应用程序的新手。 I am trying to test a model class method
add_product(product_id)
and it keeps failing though it works when i try the same on the browser. 我正在尝试测试模型类方法
add_product(product_id)
,但在我在浏览器上尝试相同的方法时,它仍然无法工作。 here is the code for the model: 这是该模型的代码:
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
Here is the failing spec for the cart model: 这是购物车模型的失败规格:
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
This fails and i get this message from 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
这失败,我从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
获得此消息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
The quantity is being updated, but you're never persisting the data. 数量正在更新,但您永远不会保留数据。 So the data is never hitting the database and the test is never going to see a change.
因此,数据永远不会到达数据库,测试也永远不会看到变化。 You'll run into the same problem with .build where it is not persisted until you explicitly say so.
您将遇到与.build相同的问题,除非明确声明,否则它不会持久存在。 You can change this by doing.
您可以这样做来更改此设置。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.