Ruby,两个对象数组的assert_equal
我有以下情况。我正在尝试为对象数组编写单元测试。该对象的定义如下:
class Element
attr_reader :title, :season, :episode
def initialize ( name, number )
@name = name
@number = number
end
def to_s
number = "%02d" % @number
result = "Number " << number << " " << @name
result
end
end
在测试期间,我断言两个数组,它们都包含三个元素,元素相同,甚至顺序相同,但我仍然收到断言不相等的错误。我想我在这里遗漏了一些非常基本的东西,有什么问题吗?
如果我通过 to_s 方法比较每个元素,则断言是正确的..这是应该首先完成的方式吗?
I have the following situation. I am trying to write a unit test for an array of objects. The object is defined something like this:
class Element
attr_reader :title, :season, :episode
def initialize ( name, number )
@name = name
@number = number
end
def to_s
number = "%02d" % @number
result = "Number " << number << " " << @name
result
end
end
During the test I assert two arrays which both contain three elements, the elements are identical and even the order is identical still I get an error that the assert isn't equal. I guess I am missing something really basic here, whats the catch?
If I compare each element by the to_s method, the assert is correct.. Is that the way it should be done in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用以下代码为您的类声明一个方法
==
。旁注,您可能也想重构您的 to_s 方法,以获得一些简洁的代码。
编辑:
Numbers 已经定义了
==
方法(https://github.com/evanphx/rubinius/blob/master/kernel/bootstrap/fixnum.rb#L117)。Ruby 通过对数组的每个元素运行
==
比较来比较数组。下面是数组上==
的实现,如 Rubinius 中所做的那样(几乎完全用 Ruby 本身编写的 Ruby 实现)https://github.com/evanphx/rubinius/blob/master/kernel/common/array.rb#L474。如果忽略各种错误检测,它基本上会递归地对数组的所有元素运行
==
,如果所有元素都匹配,则返回 true。Try declaring a method
==
for your class, with the following code.Sidenote, you might want to refactor your to_s method too, for some concise code.
Edit:
Numbers already have an
==
method defined (https://github.com/evanphx/rubinius/blob/master/kernel/bootstrap/fixnum.rb#L117).Ruby compares arrays by running an
==
compare on each element of an Array. Here's the implementation of==
on Arrays, as done in Rubinius (a Ruby implementation written almost completely in Ruby itself) https://github.com/evanphx/rubinius/blob/master/kernel/common/array.rb#L474.If you leave out various error detections, it basically runs an
==
on all the elements of the array, recursively, and returns true if all of them match.