rspecrspec-railsruby-on-rails-4.2

rspec before(:each) hook - conditionally apply


I have following in my rails_helper.rb:

RSpec.configure do |config|
  # ...
  config.before(:each, type: :controller) do
    # SOMETHING
  end
end

I want to define directories, to which this SOMETHING will be applicable (in my case ONLY to files under spec/controllers/api directory).

Any chance to achieve that?


Solution

  • You can use a more specialized name for your RSpec filter:

    RSpec.configure do |config|
      # ...
      config.before(:each, subtype: :controllers_api) do
        # SOMETHING
      end
    end
    

    And then in your RSpec examples in spec/controllers/api, you add some metadata:

    RSpec.describe "something", subtype: :controllers_api do
    end
    

    This SOMETHING will run only on examples having the subtype: :controllers_api metadata.

    To automatically derive metadata from file location, use define_derived_metadata like so:

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