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

Har*_*tty 5 ruby rspec

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

命令行

rspec --tag use_ff
Run Code Online (Sandbox Code Playgroud)

RSpec配置

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
Run Code Online (Sandbox Code Playgroud)

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

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

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
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*uth 4

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
Run Code Online (Sandbox Code Playgroud)

(我正在使用 RSpec 3.4。)