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#==
,执行类型转换.
Returns true only if
obj
is aFloat
with the same value asfloat
. Contrast this withFloat#==
, 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)