大约六个月前,我写了一个版本的fizzbuzz,并且相当确定我当时的测试覆盖率很好。我今天加载了它,并且我的大部分规格测试都失败了。最初我使用的语法to_be正确的。为了使测试覆盖率再次良好,我不得不将此语法更改为 state 为 eq true。谁能解释为什么会这样,并且我仍在正确测试?
原始语法示例
**fizzbuzz_spec.rb**
require 'fizzbuzz'
describe 'FizzBuzz' do
context 'it knows that a number is divisible by' do
it '3' do
expect(is_divisible_by_three?(3)).to be_true
end
end
end
**fizzbuzz.rb**
def is_divisible_by_three?(number)
true
end
**ERROR:** 1) FizzBuzz it knows that a number is divisible by 3
Failure/Error: expect(is_divisible_by_three?(3)).to be_true
expected true to respond to `true?`
# ./spec/fizzbuzz_spec.rb:7:in `block (3 levels) in <top (required)>'
新语法示例fizzbuzz_spec.rb 需要"嘶嘶声"
describe 'FizzBuzz' do
context 'it knows that a number is divisible by' do
it '3' do
expect(is_divisible_by_three?(3)).to eq true
end
end
end
**fizzbuzz.rb**
def is_divisible_by_three?(number)
true
end
我知道我需要扩展 def 可被方法整除的代码,我只是在这里使用 true 作为示例。
be_true
已在最新版本的RSpec中重命名为be_truthy
。
由于be_true
已被删除,因此规范可能会失败,因为该方法不再存在。
解决方案是更新代码以使用新方法。 eq(true)
有效,但略有不同:be_truthy
和be_falsey
被设计为匹配真/假相似值(例如,nil 的计算结果为 false,但不等于 false)。
如果你使用eq(true)
你假装是严格匹配的。