Ruby on rails Rails模型验证工作正常,但rake测试失败
目前,我正在学习rails。 当我使用验证格式构建模型时:Ruby on rails Rails模型验证工作正常,但rake测试失败,ruby-on-rails,regex,Ruby On Rails,Regex,目前,我正在学习rails。 当我使用验证格式构建模型时: class Product < ActiveRecord::Base validates :title, :description, :image_url, presence: true validates :price, numericality: {greater_than_or_equal_to: 0.01} validates :title, uniqueness: true validates :image_url, a
class Product < ActiveRecord::Base
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)$}i,
message: 'must be a URL for GIF, JPG or PNG image.',
multiline: true
} end
类产品
此验证用于测试图像url是否具有gif、jpg或png扩展名
当我自己运行服务器并进行测试时,一切正常。当我尝试构建模型测试时,测试没有通过
enter require 'test_helper'
class ProductTest < ActiveSupport::TestCase
def new_product(image_url)
Product.new(title: "bool",
description: "daf",
image_url: image_url)
end
test "image url" do
ok = %w{fred.gif fred.jpg fred.png RED.JPG RED.Jpg http://a.b.c/x/y/z/fesd.gif}
bad = %w{fred.doc fred.gif/more 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
输入要求的“测试\u助手”
类ProductTest
我也认为1断言是失败的:
1) 失败:ProductTest#test(测试)image(测试图像)url[/home/clark/Desktop/Agile\u Rails/depot/test/models/product(产品)test.rb 38]:
fred.gif不应该是无效的
谁能帮我一下,我的测试代码错了吗?我不知道你是否找到了它,但问题不在
图像中。您也在验证price
的数值性,但您在测试中让它为空,因此产品因price
字段而无效。我也有价格测试,请尽量保持我的问题清楚,因此我删除了代码。我认为没有价格测试也可以,因为它是逐单元运行的。您不明白。在方法new\u product
中,您创建的产品没有price
,这就是测试失败的原因。你的正则表达式非常好。哦,我明白了,我错过了新产品构造函数的价格,这就是原因。谢谢,伙计。这应该是我的错。