0

这是我的模型中的相关部分:

  belongs_to :cart
  belongs_to :product
  validate :quantity, :more_than_stock,  :message => "more than in stock is reserved." 

 def more_than_stock
    errors.add(:quantity, "should be less than in stock") if self.quantity > self.product.stock
  end

我一直在这条线上出错:errors.add(:quantity, "should be less than in stock") if self.quantity > self.product.stock关于.stock方法。

我不断得到的错误是:1) Error: test_product_id_must_be_a_number(CartRowTest): NoMethodError: undefined method 'stock' for nil:NilClass在我的测试中。

在我看来,我的测试套件不知道.stock产品上的方法。

但是,这是我的产品工厂:

factory :product do
    name 'Cholecap - 100mg'
    limit 3
    stock 10
  end

和我的 cart_row 工厂:

 factory :cart_row do
    product
    cart
    quantity 3
  end

这是我的单元测试中引发错误的相关部分:

def setup
    @cart_row = FactoryGirl.create(:cart_row)
  end

  test "product_id must not be blank" do
    @cart_row.product_id = "         "
    assert !@cart_row.valid?
  end

test "product_id must be a number" do
     @cart_row.product_id = '234'
    assert !@cart_row.valid?
  end

我需要做什么才能让测试套件知道 .stock 方法?

4

1 回答 1

1

因为您将 product_id 设置为无效值,所以您无法让测试套件知道 #stock 方法。如果您真的想让这些测试通过,请尝试以下代码:

belongs_to :cart
belongs_to :product
validates_associated :product
validate :quantity, :more_than_stock, message: "more than in stock is reserved." , if: "product.respond_to? :stock"

def more_than_stock
  errors.add(:quantity, "should be less than in stock") if quantity > product.stock
end
于 2012-09-01T06:38:24.700 回答