be_within 匹配器

普通的相等期望不适用于浮点值。考虑以下 irb 会话

  > radius = 3
    => 3
  > area_of_circle = radius * radius * Math::PI
    => 28.2743338823081
  > area_of_circle == 28.2743338823081
    => false

相反,您应该使用 be_within 匹配器来检查该值是否在您期望值的 delta 范围内

  expect(area_of_circle).to be_within(0.1).of(28.3)

请注意,实际值和期望值之间的差值必须小于您的 delta;如果相等,匹配器将失败。

基本用法

假设有一个名为“be_within_matcher_spec.rb”的文件,其中包含

RSpec.describe 27.5 do
  it { is_expected.to be_within(0.5).of(27.9) }
  it { is_expected.to be_within(0.5).of(28.0) }
  it { is_expected.to be_within(0.5).of(27.1) }
  it { is_expected.to be_within(0.5).of(27.0) }

  it { is_expected.not_to be_within(0.5).of(28.1) }
  it { is_expected.not_to be_within(0.5).of(26.9) }

  # deliberate failures
  it { is_expected.not_to be_within(0.5).of(28) }
  it { is_expected.not_to be_within(0.5).of(27) }
  it { is_expected.to be_within(0.5).of(28.1) }
  it { is_expected.to be_within(0.5).of(26.9) }
end

我运行 rspec be_within_matcher_spec.rb

那么输出应该包含所有这些

10 个示例,4 个失败
预计 27.5 不在 28 的 0.5 范围内
预计 27.5 不在 27 的 0.5 范围内
预计 27.5 在 28.1 的 0.5 范围内
预计 27.5 在 26.9 的 0.5 范围内