match 匹配器

match 匹配器在对象上调用 #match,如果 #match 返回一个真值(不是 falsenil),则通过。RegexpString 都提供 #match 方法。

  expect("a string").to match(/str/) # passes
  expect("a string").to match(/foo/) # fails
  expect(/foo/).to match("food")     # passes
  expect(/foo/).to match("drinks")   # fails

您也可以使用此匹配器在组合匹配器时匹配嵌套数据结构。

字符串用法

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

RSpec.describe "a string" do
  it { is_expected.to match(/str/) }
  it { is_expected.not_to match(/foo/) }

  # deliberate failures
  it { is_expected.not_to match(/str/) }
  it { is_expected.to match(/foo/) }
end

我运行 rspec string_match_spec.rb

那么输出应包含所有这些

4 个示例,2 个失败
期望“a string”不匹配 /str/
期望“a string”匹配 /foo/

正则表达式用法

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

RSpec.describe /foo/ do
  it { is_expected.to match("food") }
  it { is_expected.not_to match("drinks") }

  # deliberate failures
  it { is_expected.not_to match("food") }
  it { is_expected.to match("drinks") }
end

我运行 rspec regexp_match_spec.rb

那么输出应包含所有这些

4 个示例,2 个失败
期望 /foo/ 不匹配“food”
期望 /foo/ 匹配“drinks”