Rspec 测试:`eql?` 匹配器失败 [英] Rspec testing: `eql?` matcher failing

查看:56
本文介绍了Rspec 测试:`eql?` 匹配器失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写规范时遇到问题:

I am having trouble while writing specs:

 Failure/Error: expect(Question.all.count).to eql(0)

       expected: 0
            got: 0.0

       (compared using eql?)

为什么 count 返回一个浮点值,即使它没有,期望值不是 true 吗?

Why is count returning a float value, and even if it had not, wouldn't the expectation be true?

推荐答案

我不知道为什么 Question.all.count 返回 0.0,但匹配器正在工作预期的.根据文档:

I have no idea why Question.all.count returns 0.0, but the matcher is working as expected. According to the documentation:

expect(a).to equal(b) # passes if a.equal?(b)
expect(a).to eql(b)   # passes if a.eql?(b)
expect(a).to be == b  # passes if a == b

在你的情况下 expect(0.0).to eql(0) 调用:

In your case expect(0.0).to eql(0) invokes:

0.0.eql?(0) #=> false

它返回 fase 因为这就是 Float#eql? 有效:

It returns fase because that's how Float#eql? works:

仅当 obj 是与 float 具有相同值的 Float 时才返回 true.将此与 Float#==<进行对比/code>,执行类型转换.

Returns true only if obj is a Float with the same value as float. Contrast this with Float#==, which performs type conversions.

要与 a == b 进行比较,您可以使用:

To compare with a == b you would use:

expect(Question.all.count).to be == 0

expect(Question.all.count).to eq(0)

这篇关于Rspec 测试:`eql?` 匹配器失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆