使用assert_equal和.join方法通过单元测试失败,在学习《敏捷开发与Ruby on Rails》这本书时



我刚刚开始学习Ruby on Rails,甚至是Ruby语言本身。在阅读迭代B2:单元测试模型并做以下练习后:1. 验证选项:length检查模型属性的长度。向Product模型添加验证以检查标题是否至少有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">.

这是怎么发生的?我该怎么做呢?我认为这个问题与join方法有关谢谢!

代替assert_equal,试着这样使用assert_match

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

你做对了。

EDIT:如果assert_match要折旧,

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

应该产生相同的结果

相关内容

  • 没有找到相关文章

最新更新