Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access tag filters in a before(:suite)/before(:all) hook in RSpec?

Tags:

ruby

rspec

I want to access the tag filters passed in the command line

Command line

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

In the before(:suite) hook I want to access the tag filters specified in the command line in the config.

According to the rspec-core code base the inclusion tag filters are stored in inclusion_filter of RSpec.configuration. In theory I should be able to access them as follows:

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

But, for some reason, I get an empty hash even when I pass the tag from the command line.

like image 731
Harish Shetty Avatar asked Oct 21 '22 01:10

Harish Shetty


1 Answers

config.filter returns an RSpec::Core::InclusionRules. Looking in its superclass RSpec::Core::FilterRules, we see that it has an accessor .rules which returns a hash of tags, so you can do, for example,

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

(I'm using RSpec 3.4.)

like image 59
Dave Schweisguth Avatar answered Oct 23 '22 01:10

Dave Schweisguth