1

我目前正在使用 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" 属性的断言时中止。我在这里完全一无所知。任何和所有输入将不胜感激。

4

1 回答 1

0

通过仅验证标题的唯一性,您仍然允许为 nil 的标题,这会使您的测试失败。您需要将验证更改为

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
于 2014-01-07T08:35:57.447 回答