2013-04-20 85 views
1

当尝试写型号我不断收到同样的错误单元测试并不能似乎解决它。Rails的,失败的断言,没有任何消息给

这是我的测试:

require 'test_helper' 

class ProductTest < ActiveSupport::TestCase 
test "product attirbutes 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 
     # line number 19 below 
    assert product.invalid? 
    assert_equal ["must be greater than or equal to 0.01"], 
     product.errors[:price] 

    product.price = 0 
    assert product.invalid? 
    assert_equal ["must be greater than or equal to 0.01"], 
     product.errors[:price] 

    product.price = 1 
    assert product.valid? 
    end 

end 

当我运行>耙测试

我收到以下错误:

1) Failure: 
ProductTest#test_product_price_must_be_positive 
/test/models/product_test.rb:19]: 
Failed assertion, no message given. 

这里是我的模型:

class Product < ActiveRecord::Base 
validates :title, :description, :image_url, presence: true 
validates :price, numericality: {greater_then_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 

我不知道怎么回事在这里请帮助!

+1

那么,什么是第19行? – 2013-04-20 05:28:05

回答

2

由于每MINITEST ::断言docs,从“断言”派生的任何方法将引发异常消息“无法断言,没有给出消息”失败,除非你提供可选的“味精” paramater


有几件事情:

  1. 您正在测试活动记录验证,这些都是经得起考验的,图书馆的生产准备功能,所以测试是没有必要的。为了更加熟悉Active Record的验证只是去docs,然后玩弄在轨控制台

  2. 活动记录验证是你的车型只有执行时试图“创造”或“保存” 的典范。例如:

    my_user = User.create(name: nil, email: nil) # try save to DB - fails silently 
    my_user.valid? # => false 
    my_user.errors.messages # => {name:["can't be blank"], email:["can't be blank"]} 
    

也许探讨一些futher学习的话题,瑞安贝特的截屏是伟大和自由大部分。希望这有助于

注:我希望附加一些更多的链接/ refrences但是我没有点#1做

1

你的模式是错误的。

(第3行)

错)验证:价格,numericality:{greater_then_or_equal_to:0.01}

正确)验证:价格,numericality:{GREATER_THAN_OR_EQUAL_TO:0.01}

不是“然后”,但“不是”。