我目前正在通过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
我无法弄清楚为什么这个耙子被中止了。测试创建了一个空的“Product”对象,因此无效,并且每个属性都应该有错误。然而,看起来rake在击中“:title”属性的第一个断言时中止。我在这里绝对无能为力。任何和所有输入将不胜感激。
答案 0 :(得分: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