Product 的定义
class Product < ApplicationRecord
validates :title, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.[gif|jpg|png]\Z}i,
message: 'must be a URL for gif,jpg or png image.'
}
end
ProductTest 的定义
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "product attribute must not be empty" do
product = Product.new
assert product.invalid?
assert product.errors[:title].any?
assert product.errors[:description].any?
assert product.errors[:price].any?
assert product.errors[:image_url].any?
end
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 product.errors[:price],["must be greater than or equal to 0.01"]
product.price = 0
assert product.invalid?
assert_equal product.errors[:price],["must be greater than or equal to 0.01"]
product.price = 0.01
assert product.valid?
end
def new_product(image_url)
Product.new(title: "my book title",
description: "yyy",
image_url: image_url)
end
test "image_url" do
ok = %w{ fred.GIF fred.jpg fred.png Fred.JPG fred.Jpg http://a.b.c/x/y/z/fred.gif }
bad = %w{ fred.doc fred.gif/mor fred.gif.more }
ok.each do |name|
assert new_product(name).valid?, "#{name} shouldn't be invalid"
end
bad.each do |name|
assert new_product(name).invalid?, "#{name} shouldn't be valid"
end
end
end
运行 bin/rails test:models 后报错,有时候是报错 test_product_price_must_be_positive,有时候是报错 test_image_url
Failure:
ProductTest#test_product_price_must_be_positive [/Users/sun/Desktop/rubywork/depot/test/models/product_test.rb:29]:
Expected false to be truthy.
Failure:
ProductTest#test_image_url [/Users/sun/Desktop/rubywork/depot/test/models/product_test.rb:44]:
fred.GIF shouldn't be invalid```