rubyrspecrequirebefore-filter

How to use require_relative with an rspec test?


I have an rspec test, i.e. describe and an it

I want to add before :all and before :each behavior

I can add it by putting in the test spec file directly, i.e.

describe "test" do
  before :all do
    CONTINUE_SPEC= true
  end

  around :each do |example|
    if CONTINUE_SPEC
      CONTINUE_SPEC = false
      example.run
      CONTINUE_SPEC = true unless example.exception
    else
      example.skip
    end
  end
  ... actual tests...

However I want to have it in nearly every spec so I thought I could use a require_relative statement to make it easy. However when I transfer the code to a file using require_relative with

require_relative '../../support/continue_test_if_passing'

I get

Failure/Error:
  before :all do
    CONTINUE_SPEC= true
  end

NoMethodError:
  undefined method `before' for main:Object

Solution

  • Just add this to your spec_helper.rb in the RSpec.configure block:

    RSpec.configure do |config|
      config.before :all do
        CONTINUE_SPEC= true
      end
    
      config.around :each do |example|
        if CONTINUE_SPEC
          CONTINUE_SPEC = false
          example.run
          CONTINUE_SPEC = true unless example.exception
        else
          example.skip
        end
      end
    
      # ...
    end