【问题标题】:Rails model validation works, but rake test failRails 模型验证有效,但 rake 测试失败
【发布时间】:2015-05-08 16:26:14
【问题描述】:

目前,我正在学习 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, allow_blank: true, format: {
    with:   %r{\.(gif|jpg|png)$}i,
    message: 'must be a URL for GIF, JPG or PNG image.',
    multiline: true
} end

这个验证是为了测试image_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

我也认为 1 断言失败:

1) 失败:
ProductTest#test_image_url [/home/clark/Desktop/Agile_Rails/depot/test/models/product_test.rb 38]:
fred.gif 不应该是无效的

谁能帮帮我,我的测试代码错了吗?

【问题讨论】:

    标签: ruby-on-rails regex


    【解决方案1】:

    我不知道你是否找到它,但问题不在image_url 中。您还在验证 price 的数字,但您在测试中将其留空,因此产品由于 price 字段而无效。

    【讨论】:

    • 我也有价格测试,只是尽量保持我的问题干净,所以我删除了代码。
    • 而且我认为没有价格测试也没关系,因为它是逐个运行的。
    • 你不懂。在方法new_product 中,您正在创建没有price 的产品,这就是您的测试失败的原因。你的正则表达式绝对没问题。
    • 哦,我明白了,我错过了 new_product 构造函数中的价格,这就是原因。
    • 谢谢,伙计。这应该是我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多