2012-07-17 21 views
1

我目前正在使用Agile Development With Rails第4版(Rails 3.2+)。我想大跳单元测试的“产品”的模式:耙测试:单元中止,但为什么?

require 'test_helper' 

class ProductTest < ActiveSupport::TestCase 
    test "product attributes 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 
end 

这是什么字书中有一句话,没有勘误表说,否则。当我运行:

rake test:units 

我回来了以下内容:

Run options: 

# Running tests: 

F 

Finished tests in 0.079901s, 12.5155 tests/s, 25.0310 assertions/s. 

    1) Failure: 
test_product_attributes_must_not_be_empty(ProductTest) [/Users/robertquinn/rails_work/depot/test/unit/product_test.rb:7]: 
Failed assertion, no message given. 

1 tests, 2 assertions, 1 failures, 0 errors, 0 skips 
rake aborted! 
Command failed with status (1): [/Users/robertquinn/.rvm/rubies/ruby-1.9.3-...] 

Tasks: TOP => test:units 
(See full trace by running task with --trace) 
Robert-Quinns-MacBook-Pro:depot robertquinn$ 

这里是我的产品模型验证:

class Product < ActiveRecord::Base 
    attr_accessible :description, :image_url, :price, :title 

    validates :description, :image_url, :price, 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.' 
    } 
end 

我想不通为什么这个耙被中止。测试创建了一个空的“产品”对象,因此它是无效的,并且应该对每个属性都有错误。但是,看起来rake在对“:title”属性点击第一个断言后中止。我在这里绝对无能为力。任何和所有的输入将不胜感激。

+0

它放弃,因为你的测试失败。取消每个断言的注释,找出哪一个失败并从那里开始。 – 2012-07-17 09:40:42

+0

那么您对产品模型有什么验证? – Frost 2012-07-17 10:00:18

+0

单独评论每个断言后,导致问题的那个是“断言product.errors [:title] .any?”作为回应,我删除了:title“validates:title,uniqueness:true”的验证,看看是否可以解决它,但仍然没有运气。 – flyingarmadillo 2012-07-17 10:06:41

回答

0

通过只验证标题的唯一性,您仍然允许标题为零,这会使测试失败。你需要改变你的验证

validates :title, presence: true, uniqueness: true 

我还建议你添加消息到你的断言。这使得它更容易看到哪些断言失败:

require 'test_helper' 

class ProductTest < ActiveSupport::TestCase 
    test "product attributes must not be empty" do 
    product = Product.new 
    assert product.invalid?, "Empty product passed validation" 
    assert product.errors[:title].any?, "Missing title passed validation" 
    assert product.errors[:description].any?, "Missing description passed validation" 
    assert product.errors[:price].any?, "Missing price passed validation" 
    assert product.errors[:image_url].any?, "Missing image URL passed validation" 
    end 
end 
相关问题