定义具有流畅接口的匹配器

使用 chain 方法定义具有流畅接口的匹配器。

带有参数的链式方法

给定一个名为“between_spec.rb”的文件,其中包含

RSpec::Matchers.define :be_bigger_than do |first|
  match do |actual|
    (actual > first) && (actual < @second)
  end

  chain :and_smaller_than do |second|
    @second = second
  end
end

RSpec.describe 5 do
  it { is_expected.to be_bigger_than(4).and_smaller_than(6) }
end

我运行 rspec between_spec.rb --format documentation

输出应包含“1 个示例,0 个失败”。

并且输出应包含“预期大于 4”。

链式 setter

给定一个名为“between_spec.rb”的文件,其中包含

RSpec::Matchers.define :be_bigger_than do |first|
  match do |actual|
    (actual > first) && (actual < second)
  end

  chain :and_smaller_than, :second
end

RSpec.describe 5 do
  it { is_expected.to be_bigger_than(4).and_smaller_than(6) }
end

我运行 rspec between_spec.rb --format documentation

输出应包含“1 个示例,0 个失败”。

并且输出应包含“预期大于 4”。

include_chain_clauses_in_custom_matcher_descriptions 配置为 true 且带有参数的链式方法时

给定一个名为“between_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.include_chain_clauses_in_custom_matcher_descriptions = true
  end
end

RSpec::Matchers.define :be_bigger_than do |first|
  match do |actual|
    (actual > first) && (actual < @second)
  end

  chain :and_smaller_than do |second|
    @second = second
  end
end

RSpec.describe 5 do
  it { is_expected.to be_bigger_than(4).and_smaller_than(6) }
end

我运行 rspec between_spec.rb --format documentation

输出应包含“1 个示例,0 个失败”。

并且输出应包含“预期大于 4 且小于 6”。