我正在阅读“使用 Rails 进行敏捷 Web 开发”,但我无法理解单元测试。
有一个这样定义的模型:
class Product < ActiveRecord::Base
# .....
validates :price, numericality: {greater_than_or_equal_to: 0.01}
# .....
end
和测试:
test "product price must be positive" do
product = Product.new(
title: "my title",
description: "yyy",
image_url: "zzz.jpg",
)
product.price = -1
assert product.invalid?
assert_equal ["must be greater than or equal to 0.01"],
product.errors[:price]
product.price = 0
assert product.invalid?
assert_equal ["must be greater than or equal to 0.01"],
product.errors[:price]
product.price = 1
assert product.valid?
end
为什么我们需要这个:
assert_equal ["must be greater than or equal to 0.01"],
product.errors[:price]
为什么要比较错误消息?而不是编写这样的测试:
product.price = -1
assert product.invalid?, "must be greater than or equal to 0.01"
product.price = 0
assert product.invalid?, "must be greater than or equal to 0.01"