你可以将匹配器传递给rspec中的共享示例吗?

时间:2018-05-08 10:15:19

标签: rspec

我有以下情况。我有一个共享示例,它在一些哈希中作为数据传递,另一个哈希与预期数据一起传递。简化它看起来像这样:

RSpec.describe "shared examples" do
  shared_examples "matching hash" do |data, expected_data|
    it 'matches' do
      expect(data).to include (expected_data)
    end
  end

  it_behaves_like "matching hash", { foo: '/foo/1', bar: '/bar' }, { foo: '/foo/1' }
end

我现在遇到的问题是,对于包含URL的哈希中的某些值,我不想检查完整的字符串,而只检查开始。所以我的想法是使用像我通常那样的匹配器并将其传递到expected_data内。

RSpec.describe "shared examples with passed in matcher" do
  shared_examples "matching hash" do |data, expected_data|
    it 'matches' do
      expect(data).to include (expected_data)
    end
  end

  it_behaves_like "matching hash", { foo: '/foo/1' }, { foo: start_with('/foo/') }
end

可悲的是,

失败了
Failure/Error: it_behaves_like "matching hash", { foo: '/foo/1' }, { foo: start_with('/foo/') }
  `start_with` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).

在这种特定情况下,我可以通过传递正则表达式而不是start_with来解决它,或者调整共享示例以显式获取模糊数据并通过匹配器进行比较。

但对我而言,如果有一种方法可以将匹配器传递给共享示例,那会感觉更好。有没有办法做到这一点,或者这是不可能的?

0 个答案:

没有答案