面试题答案
一键面试- 步骤:
- 首先,使用
RSpec::Matchers.define
方法来定义一个新的匹配器。 - 在匹配器定义块中,设置
matches?
方法,该方法接收要测试的数组作为参数,并检查数组中的所有元素是否都大于0。 - 同时,设置
failure_message
和failure_message_when_negated
方法,用于在匹配失败时提供有意义的错误信息。
- 首先,使用
- 代码实现:
RSpec::Matchers.define :all_positive do
matches? do |array|
array.all? { |element| element > 0 }
end
failure_message do |array|
"expected all elements in #{array} to be positive"
end
failure_message_when_negated do |array|
"expected some elements in #{array} to be non - positive"
end
end
在测试中使用这个匹配器:
describe 'Custom Matcher' do
it 'should pass when all elements are positive' do
expect([1, 2, 3]).to all_positive
end
it 'should fail when some elements are non - positive' do
expect([1, -2, 3]).not_to all_positive
end
end