我正在学习 Rails,并且正在学习单元测试。我正在使用的其中一本书给出了一个显然写错的例子。
这是验证:
class Product < ActiveRecord::Base
attr_accessible :description, :image_url, :price, :title
#VALIDATION PROCESS
validates :title, :description, :image_url, :presence => true, :length => {:minimum => 10}
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
validates :image_url, :format => {
:with => %r{\.(gif|jpg|png)$}i,
:message => 'Must be a URL for GIF,PNG or JPG image!'
}
end
这是测试:
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
test "product price must be positive" do
product = Product.new(:title => "My Book 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].join('; ' )
product.price = 0
assert product.invalid?
assert_equal "must be greater than or equal to 0.01" ,
product.errors[:price].join('; ' )
product.price = 1
assert product.valid?
end
end
当我在命令行上使用 运行测试时rake test:units
,最后一个断言失败:
product.price = 1
assert product.valid?
它说Failured assertion, no message given
。
奇怪的是,这本书本身就说这个特定的断言是正确的,所以在测试期间应该什么都不会发生。
那么,这是怎么回事?代码是错误的,还是我做错了什么,或者是正确的,我只是感到困惑?