Ruby:断言由Set的子类生成的错误消息

时间:2014-01-01 02:52:50

标签: ruby error-handling set assert

require 'set'
require 'test/unit'
class Foo < Set
  def to_s
    "to_s"
  end
  alias_method :inspect, :to_s
end

class FooTest < Test::Unit::TestCase
  def test1
    assert_equal(Foo.new, false)
  end
end

预期产出:

test1(FooTest) [test.rb:12]: <to_s> expected but was <false>.

实际输出:

test1(FooTest) [test.rb:12]: <#<Foo: {}>> expected but was <false>.

修改

Test :: Unit使用了一个名为pretty_inspect的奇怪方法,这是我第一次听到的。不过,此代码将按预期工作:

解决方案:

require 'set'
require 'test/unit'
class Foo < Set
  def to_s
    "to_s"
  end
  alias_method :pretty_inspect, :to_s
end

class FooTest < Test::Unit::TestCase
  def test1
    assert_equal(Foo.new, false)
  end
end

1 个答案:

答案 0 :(得分:0)

test / unit似乎不依赖于对象的to_sinspect方法。查看源代码,它可能直接访问对象的类inspect方法,但我尝试重新定义Set inspect实例方法也不起作用。查看测试/单元的来源。 ; - )