【问题标题】:Length Validation Testing Rails Test:Unit长度验证测试 Rails Test:Unit
【发布时间】:2015-12-01 03:31:31
【问题描述】:

我刚刚进入 Rails 测试,我使用的是内置的测试“语言”,而不是 Rspec。对于我的生活,我无法弄清楚为什么这仍然失败。

test "product title is at least 10 chars long" do
    product = Product.new(description: 'yyy',
                          image_url: 'zzz.jpg',
                          price: 1)
    product.title = 'testitout'
    assert product.invalid?
    assert_equal ['title must be at least 10 chars long'], product.errors[:title]

    product.title = 'testitoutt'
    assert product.valid?
end

这是 Product.rb

class Product < ActiveRecord::Base
  validates :title, :description, :image_url, 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)\Z}i,
    message: 'must be a URL for GIF, JPG, or PNG'
  }
  validates :title, length: { minimum: 10 }
end

这是我的终端告诉我的。

1) Failure:
ProductTest#test_product_title_is_at_least_10_chars_long [/test/models/product_test.rb:62]:
--- expected
+++ actual
@@ -1 +1 @@
-["Title is too short (minimum is 10 characters)"]
+[]


5 runs, 23 assertions, 1 failures, 0 errors, 0 skips

【问题讨论】:

  • 什么失败了?你的product.errors[:title] 应该等于["is too short (minimum is 10 characters)"]
  • Nvm 我想通了。谢谢。

标签: ruby-on-rails testing tdd testunit


【解决方案1】:

我也在学习这个,这是我发现的解决方法。

assert 行中的消息必须与 Rails 在浏览器中输出的内容相匹配(减去 Title 部分)。

所以在浏览器中,当你的标题太短时,它会闪烁这个错误消息:

所以我们可以测试的文本是:'太短(最少 10 个字符)'

让你的 assert_equal 行:

assert_equal ['is too short (minimum is 10 characters)'], product.errors[:title]

那么你的测试就通过了。

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    相关资源
    最近更新 更多