Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set global RSpec metadata?

Tags:

ruby

rspec

I have a script that wraps around tests in RSpec 3.4.4 and causes them to timeout after ten seconds.

TIMEOUT = 10

RSpec.configure do | config |
  config.around do |example|
    timeout = Float(example.metadata[:timeout]) rescue TIMEOUT
    begin
      Timeout.timeout(timeout) { example.run }
    rescue Timeout::Error
      skip "Timed out after #{timeout} seconds"
    end
  end
end

This script is in a central location - ~/lib/spec_helper.rb - and is required by spec_helpers in my repositories.

I would like to be able to configure example.metadata[:timeout] at a repository-wide level, to have all of its specs time out (for example) after two seconds, or (for another example) not at all.

I've tried setting it as an option in .rspec - a solution which would be ideal for me - but of course it doesn't recognise custom options like that. I would expect the command line to do exactly the same thing.

Is there a way to set metadata for all examples in a test suite?

like image 663
PJSCopeland Avatar asked Nov 23 '16 01:11

PJSCopeland


1 Answers

The define_derived_metadata option does exactly what you want:

define_derived_metadata(*filters) {|metadata| ... } ⇒ void

RSpec.configure do |config|
 # Tag all groups and examples in the spec/unit directory with
 # :type => :unit
 config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata|
  metadata[:type] = :unit
 end
end

Check it on rubydoc.info

like image 92
Myron Marston Avatar answered Oct 13 '22 05:10

Myron Marston