How can I access metadata in rspec before(:all)?

Inside a before(:all) block, there is no "running example", but you can still access the metadata through the RSpec::Core::ExampleGroup. Here's an example of how you can access the metadata from various scopes:

describe "My app", js: true do

  context "with js set to #{metadata[:js]}" do
    before :all do
      puts "in before block: js is set to #{self.class.metadata[:js]}"
    end

    it "works" do
      puts "in example: js is set to #{example.metadata[:js]}"
    end
  end

end

For more information, please take a look at this comment in rspec/rspec-core#42.


This is not exactly answering the original question, but it is related and this was the first post related to my Google search, so I'd like to share what I just figured out.

In my case, I was looking for a way to run some commands in a before(:suite)/before(:all), but only if the tests being run included some system tests (aka examples with certain metadata). Here's what I came up with:

RSpec.configure do |config|
  config.before(:suite) do
    examples = RSpec.world.filtered_examples.values.flatten
    has_system_tests = examples.any? { |example| example.metadata[:type] == :system }

    if has_system_tests
      ...
    end
  end
end

Tags:

Ruby

Rspec2