在 rspec 外部定义匹配器
在 rspec-core 之外使用 rspec-expectations 时,可以定义自定义匹配器。
定义具有默认消息的匹配器
假设一个名为“test_multiples.rb”的文件,其中包含
require "minitest/autorun"
require "rspec/expectations/minitest_integration"
RSpec::Matchers.define :be_a_multiple_of do |expected|
match do |actual|
actual % expected == 0
end
end
class TestMultiples < Minitest::Test
def test_9_should_be_a_multiple_of_3
expect(9).to be_a_multiple_of(3)
end
def test_9_should_be_a_multiple_of_4
expect(9).to be_a_multiple_of(4)
end
end
当我运行 ruby test_multiples.rb
那么退出状态不应为 0
并且输出应包含“预期 9 是 4 的倍数”
并且输出应包含“2 次运行,2 个断言,1 个失败,0 个错误”。