【问题标题】:why are brackets used in this assert_equal statement为什么在这个 assert_equal 语句中使用括号
【发布时间】:2012-11-04 20:06:18
【问题描述】:

在《Agile Web Development with Rails》一书中,他们正在教授如何编写测试单元用例:

test "product price must be positive" do
  product = Product.new(title: "By Book Title",
                        description: "yyy",
                        image_url: "zzz.jpg")
  product.price = -1
  assert product.invalid?
  assert_equal ["must be greater than or equal to 0.01"], product.errors[:price]
end

关于 assert_equal 语句,为什么“必须大于...”字符串需要括号。我假设变量类型在这里发挥作用,但需要澄清原因。

谢谢。

【问题讨论】:

    标签: ruby-on-rails unit-testing variable-types


    【解决方案1】:

    model.errors[:field] 总是返回一个字符串数组,即使只有一个错误。

    如果断言是在没有 [ ] 的情况下完成的,则它始终为 false,因为它将字符串与数组进行比较。

    assert_equal "must be greater than or equal to 0.01", ["must be greater than or equal to 0.01"]    
    => false
    
    assert_equal ["must be greater than or equal to 0.01"], ["must be greater than or equal to 0.01"]   
    => true
    

    【讨论】:

    • 啊哈!因此,如果该字段有多个错误,assert_equal 会尝试与其他返回的错误匹配,还是仅尝试匹配第一个错误?
    • 如果该字段有多个错误,则断言将失败。数组的所有内容/元素必须相同。
    • 所以,听起来可能有更好的方法来做到这一点,我将在本书后面学习。感谢您帮助我了解类型问题!
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多