0

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

4

1 回答 1

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
于 2013-08-06T10:25:11.200 回答