V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yoyicue
V2EX  ›  Ruby on Rails

有一个关于断言的小疑问

  •  
  •   yoyicue · 2011-03-29 13:26:28 +08:00 · 4872 次点击
    这是一个创建于 4748 天前的主题,其中的信息可能已经有所发展或是发生改变。


    我的思维转不过弯了
    expected 与 actual 符合的时候 assert_equal 是 true.
    例子中这个 assert_equal
    如何在 rake test:units 中把
    xxxx has already been taken
    打印在屏幕上?
    7 条回复    1970-01-01 08:00:00 +08:00
    yoyicue
        1
    yoyicue  
    OP
       2011-03-29 14:48:08 +08:00
    囧. 是我当时傻了. 大家无视我吧. 此文应该属于 "无要点"
    ----------------------------

    #为毛断言 assert_equal 的 message 没有 print 出来呢? 如何 print 出来?

    首先说改成下面这句就会出现,
    assert_equal "has already been taken :(", product.errors[:title].join('; ')

    错在理解上, 以为测试为 true 时会 print 一条
    xxxx has already been taken
    但实际上 true 怎么会有message?

    其实
    assert 的 message 是 false 的时候才会触发
    assert_equal 是说 expected 与 actual 为 false 的时候 才会触发fail message

    assert_equal "has already been taken", product.errors[:title].join('; ')
    例子中这一句实际的目的是验证 product.errors[:title].join('; ') 的消息是不是 "has already been taken",
    如果不符合例子的预期(false) 才会 print 出来

    代码里是将 ActiveRecord 的错误信息 硬编码到了字符串
    就是说知道 activerecord.errors.messages.taken 在英文里默认的错误信息就是 "has already been taken".
    之所以不会出现, 是因为每次出错的信息确实是 "has already been taken" 符合预期(true)

    btw:
    #join('; ')的作用?
    .product.errors[:title] 本身可能是个array,
    包含多个错误, 按照.join('; ')的方式进行合并成string后进行对比
    虽然目前遇不到多个, 但是严谨对待测试用例, 所以要带上

    #这两种使用有什么区别?
    assert_equal('1234',connection.key)
    assert_equal "has already been taken", product.errors[:title].join('; ')
    应该没什么区别
    chloerei
        2
    chloerei  
       2011-03-29 14:57:10 +08:00
    感觉测试 error message 的内容有点粒度太小了,我一般就测 valid? 或者 errors.include?(:title)

    因为万一 error message 的内容变了就成为不必要的麻烦了。
    yoyicue
        3
    yoyicue  
    OP
       2011-03-29 15:03:00 +08:00
    @chloerei
    我初学 买了本 Agile Web Development with Rails 4th edition 看着做的.

    即便出现 "因为万一 error message 的内容变了" , QA 不正好测出来了么?
    当然我也不喜欢硬编码 感觉不稳定 缺少安全感
    chloerei
        4
    chloerei  
       2011-03-29 15:06:23 +08:00
    @yoyicue 比如有人部署的时候将 default_locale 设成了 zh-CN,那error message 就全变成中文通不过测试了。或者官方的 error message 心血来潮加了个 . 号。
    yoyicue
        5
    yoyicue  
    OP
       2011-03-29 15:08:06 +08:00
    @chloerei 恩 恩 作者给了 I18n.translate('activerecord.errors.messages.taken')
    chloerei
        6
    chloerei  
       2011-03-29 15:10:48 +08:00
    @yoyicue 奥,这个不错,要准确匹配什么校验出错用这个好。translate 可以简写为 t
    yoyicue
        7
    yoyicue  
    OP
       2011-03-29 15:14:59 +08:00
    @chloerei 多谢 我喜欢简写 XD
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5427 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 08:39 · PVG 16:39 · LAX 01:39 · JFK 04:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.