簡體   English   中英

在使用《 Ruby on Rails上的敏捷開發》一書學習RoR時,使用assert_equal和.join方法無法通過單元測試

[英]using assert_equal and .join metho failed pass the unit testing, when learning RoR with the book Agile Development with Ruby on Rails

我剛剛開始學習Ruby on Rails,甚至是Ruby語言本身。 閱讀完迭代B2:模型的單元測試並進行以下練習后:1.驗證選項:length檢查模型屬性的長度。 將驗證添加到產品模型中,以檢查標題長度至少為10個字符。 2.更改與您的一項驗證關聯的錯誤消息。

我將以下代碼放入/models/product.rb

validates_uniqueness_of :title, :message => 'has already been taken'
validates_length_of :title, :minimum => 8, :message => 'must be at least 8 letters'

並將以下鱈魚放入/unit/product_test.rb

test "product is not valid without a 8 letters title" do
product = Product.new(:title =>"12345678",
                      :description => "yyy",
                      :price => 1,
                      :image_url => "fred.gif")
product.title = "abcdefg"
assert product.invalid?
assert_equal "must be at least 8 letters", product.errors[:title].join('; ')
product.title = "abcdefgh"
assert product.valid?    
end

test "product is not valid without a unique title" do
product = Product.new(:title => products(:lighting).title,
                      :description => "yyy",
                      :price => 1,
                      :image_url => "fred.gif")
assert !product.save
assert_equal "has already been taken", product.errors[:title].join('; ')

end

但是當我運行rake測試時,出現了一個失敗,我不知道如何解決它,它顯示:

1) Failure:
test_product_is_not_valid_without_a_unique_title(ProductTest)
/Users/youngoo/Development/RubyonRails/anaheim/test/unit/product_test.rb:66]:
<"has already been taken"> expected but was
<"has already been taken; must be at least 8 letters">.

怎么發生的? 以及我該怎么辦? 我以為問題與加入方法有關,謝謝!

代替assert_equal ,嘗試像這樣使用assert_match

assert_match /has already been taken/, product.errors[:title].join('; ')

您走在正確的軌道上。

編輯:如果assert_match要折舊,

assert_not_nil /has already been taken/.match(product.errors[:title].join('; ')

應該產生相同的結果

暫無
暫無

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

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