簡體   English   中英

抽水測試:部隊中止了,為什么?

[英]rake test:units aborted but why?

我目前正在通過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”對象,該對象因此無效,並且每個屬性都應該有錯誤。 但是,耙向“:title”屬性命中第一個斷言后,耙似乎中止了。 我在這里絕對一無所知。 任何和所有輸入將不勝感激。

通過僅驗證標題的唯一性,您仍然允許標題為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM