start_with 匹配器

使用start_with 匹配器指定字符串或数组以预期的字符或元素开头。

  expect("this string").to start_with("this")
  expect("this string").not_to start_with("that")
  expect([0,1,2]).to start_with(0, 1)

使用字符串

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

RSpec.describe "this string" do
  it { is_expected.to start_with "this" }
  it { is_expected.not_to start_with "that" }

  # deliberate failures
  it { is_expected.not_to start_with "this" }
  it { is_expected.to start_with "that" }
end

我运行rspec example_spec.rb

那么输出应该包含所有这些

4 个示例,2 个失败
预期“this string”不以“this”开头
预期“this string”以“that”开头

使用数组

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

RSpec.describe [0, 1, 2, 3, 4] do
  it { is_expected.to start_with 0 }
  it { is_expected.to start_with(0, 1)}
  it { is_expected.not_to start_with(2) }
  it { is_expected.not_to start_with(0, 1, 2, 3, 4, 5) }

  # deliberate failures
  it { is_expected.not_to start_with 0 }
  it { is_expected.to start_with 3 }
end

我运行rspec example_spec.rb

那么输出应该包含所有这些

6 个示例,2 个失败
预期[0, 1, 2, 3, 4]不以0开头
预期[0, 1, 2, 3, 4]以3开头