以下是我的模型中的相关部分:
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方法?
答案 0 :(得分: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