RSPEC测试期望内存值相同吗?

发布于 2025-02-13 17:34:45 字数 852 浏览 0 评论 0原文

我的RSPEC测试失败了,我不明白如何解决它。

似乎错误是因为它们是对象的不同实例,因此它们获得了不同的内存值。

当创建一个对象,如果给出相同的输入,则如何保持内存值对象?

describe '#==' do
let(:cpf) {described_class.new('01201201202')}

it 'verifies the key equality' do
    expect(cpf).to eq described_class.new('01201201202')

错误:

 1) PixKey#== verifies the key equality
 Failure/Error: expect(cpf).to eq described_class.new('01201201202')

   expected: #<PixKey:0x0000018d191b8670 @value="01201201202", @key="01201201202", @type="cpf">
        got: #<PixKey:0x0000018d191b8b70 @value="01201201202", @key="01201201202", @type="cpf">

   (compared using ==)

   Diff:
   @@ -1,4 +1,4 @@
   -#<PixKey:0x0000018d191b8670
   +#<PixKey:0x0000018d191b8b70
     @key="01201201202",
     @type="cpf",
     @value="01201201202">

任何想法都会很棒。

I have this Rspec test that is failing and i'm not understanding how to solve it.

it seems like the error is because they are differents instances of the object, so they got differents memory values.

How can i maintain a memory value object when create a object that will behaviour in the same way if given the same input?

describe '#==' do
let(:cpf) {described_class.new('01201201202')}

it 'verifies the key equality' do
    expect(cpf).to eq described_class.new('01201201202')

Error:

 1) PixKey#== verifies the key equality
 Failure/Error: expect(cpf).to eq described_class.new('01201201202')

   expected: #<PixKey:0x0000018d191b8670 @value="01201201202", @key="01201201202", @type="cpf">
        got: #<PixKey:0x0000018d191b8b70 @value="01201201202", @key="01201201202", @type="cpf">

   (compared using ==)

   Diff:
   @@ -1,4 +1,4 @@
   -#<PixKey:0x0000018d191b8670
   +#<PixKey:0x0000018d191b8b70
     @key="01201201202",
     @type="cpf",
     @value="01201201202">

Any ideas would be great.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱的故事 2025-02-20 17:34:46

==方法的默认行为返回true当两个对象都涉及相同的哈希键时。因为在您的示例中,两个元素都是不同的实例,它们的哈希值将有所不同。

如果您希望两个实例的pixkey如果它们具有相同的@value和/或@key默认实现与您自己的实现,例如这样:

# in your `PixKey` class
def ==(other)
  self.class == other.class && @key == other.key && @value == other.value
end

The default behavior of the == method returns true when both objects refer to the same hash key. Because in your example both elements are different instances their hash value would be different.

If you want two instances of PixKey to be considered equal if they have the same @value and/or @key then you need to override the default implementation with your own implementation, for example like this:

# in your `PixKey` class
def ==(other)
  self.class == other.class && @key == other.key && @value == other.value
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文