在rspec中编写自定义匹配器

时间:2015-03-20 08:16:25

标签: ruby testing rspec matcher

我刚刚从java dev切换到Ruby / Python。我的任务是在rspec中编写自定义匹配器。我习惯在java中使用像hamcrest和Shazamcrest这样的工具(很棒)。他们在rspec中的任何这样的工具会让我的生活更轻松吗?

1 个答案:

答案 0 :(得分:0)

自定义匹配器的示例:

require 'rspec/expectations'

RSpec::Matchers.define :be_a_multiple_of do |expected|
  match do |actual|
    actual % expected == 0
  end
end

RSpec.describe 9 do
  it { is_expected.to be_a_multiple_of(3) }
end

RSpec.describe 9 do
  it { is_expected.not_to be_a_multiple_of(4) }
end

# fail intentionally to generate expected output
RSpec.describe 9 do
  it { is_expected.to be_a_multiple_of(4) }
end

# fail intentionally to generate expected output
RSpec.describe 9 do
  it { is_expected.not_to be_a_multiple_of(3) }
end

检查为RSpec here编写自定义匹配器的文档!

祝你好运!