Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...