Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

ruby on rails - Rspec testing: `eql?` matcher failing

I am having trouble while writing specs:

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

       expected: 0
            got: 0.0

       (compared using eql?)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

0.0.eql?(0) #=> false

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

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

To compare with a == b you would use:

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

or

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...