如何在RSpec中的before(:suite)/ before(:all)钩子中访问标记过滤器?

时间:2014-09-28 01:48:47

标签: ruby rspec

我想访问命令行中传递的标记过滤器

命令行

rspec --tag use_ff

RSpec config

RSpec.configure do |config|
  config.before :suite, type: :feature do 
    # how do I check if use_ff filter was specified in the command line?
    if filter[:use_ff]
      use_selenium
    else
      use_poltergeist
    end
  end
end

before(:suite)挂钩中,我想访问配置中命令行中指定的标记过滤器。

根据rspec-core代码库,包含标记过滤器存储在RSpec.configuration的inclusion_filter中。从理论上讲,我应该能够按如下方式访问它们:

RSpec.configure do |config|
  config.before :suite, type: :feature do 
    if config.filter[:use_ff] # filter is an alias for inclusion_filter
      use_selenium
    else
      use_poltergeist
    end
  end
end

但是,出于某种原因,即使我从命令行传递了标记,我也会得到一个空哈希。

2 个答案:

答案 0 :(得分:3)

config.filter返回RSpec::Core::InclusionRules。查看它的超类RSpec::Core::FilterRules,我们看到它有一个访问器.rules,它返回一个标签的哈希,所以你可以做,例如,

RSpec.configure do |config|
  config.before(:suite) do
    $running_only_examples_tagged_foo = config.filter.rules[:foo]
  end
end

describe "Something" do
  it "knows we're running only examples tagged foo", :foo do
    expect($running_only_examples_tagged_foo).to be_truthy # passes
  end
end

(我正在使用RSpec 3.4。)

答案 1 :(得分:0)

@Dave Schweisguth 的回答很好,但请注意,您不能再使用 --only-failures 选项。

(不幸的是,--only-failures 不适用于标签过滤器)

相关问题