简体   繁体   English

Rails模型验证有效,但耙测试失败

[英]Rails model validation works, but rake test fail

Currently, i'm learning rails. 目前,我正在学习Rails。 When i build a model with validation format: 当我使用验证格式构建模型时:

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

this validation is to test whether the image_url has an extension with gif, jpg or png. 此验证用于测试image_url是否具有gif,jpg或png扩展名。

When i run the server and test by myself, everything work fine. 当我运行服务器并自己进行测试时,一切正常。 While when i try to build the model test, test not pass. 当我尝试构建模型测试时,测试未通过。

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

It also through me that 1 assert is failure: 也通过我,1断言是失败:

1) Failure: 1)失败:
ProductTest#test_image_url [/home/clark/Desktop/Agile_Rails/depot/test/models/product_test.rb 38]: ProductTest#test_image_url [/home/clark/Desktop/Agile_Rails/depot/test/models/product_test.rb 38]:
fred.gif shouldn't be invalid fred.gif不应无效

Can anybody help me, is my testing code wrong? 有人可以帮我吗,我的测试代码错误吗?

I don't know if you found it yet but problem is not in the image_url . 我不知道您是否找到它,但是问题不在image_url You are validating also price for numericality but you are letting it blank in your test so product is invalid because of price field. 您还在验证数字的price ,但是在测试中将其留为空白,因此由于price字段,产品无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM