How to set global RSpec metadata?

I have a script that wraps tests in RSpec 3.4.4 and calls their timeout in 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 centrally located - ~/lib/spec_helper.rb - and require d on spec_helper in my repositories.

I would like to be able to configure example.metadata[:timeout] at the entire repository level so that all its specification timeout (for example) after two seconds, or (for another example) not at all.

I tried installing it as an option in .rspec - a solution that would be ideal for me, but, of course, it does not recognize user parameters. I would expect the command line to do the same.

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

+5
source share
2 answers

Besides hacking the internal components of RSpec, which is probably not a good idea, the only way to do this is to abuse the available option:

The tag parameter is a good candidate for this, since it allows you to enter key / value pairs. The advantage of this is that it can be installed in a .rspec file and can be overridden by a command line argument. For instance,

.rspec configuration

 --format documentation --color --tag timeout:10 --require spec_helper 

command line

 rspec --tag timeout:2 

You just need to be careful and make sure that you remove the tag from the filter or all tests are filtered out ... To use this, in your case, you simply do:

 RSpec.configure do | config | timeout = config.filter.delete(:timeout) || 10 config.around do |example| begin Timeout.timeout(timeout) { example.run } rescue Timeout::Error skip "Timed out after #{timeout} seconds" end end end 

In this particular example, setting the timeout to zero will disable the use of timeouts.

The order of priority from highest to lowest is command line arg > .rspec configuration > default specified in your config block .

+1
source

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 out at rubydoc.info

+1
source

Source: https://habr.com/ru/post/1260176/


All Articles