Search code examples
ruby-on-railsrspecrspec-rails

How to include shared context to every spec in rails


I have a shared context:

shared_context :current_country do
  let!(:country) { create :country, slug: "kw" } unless Country.find_by(slug: "kw").present?
end

I need to have access to the country variable in each spec.

To use it, I need to include_context :current_country in every spec file. Is it possible to avoid having this line in each spec file and instead configure the context to be available everywhere?


Solution

  • You can declare your shared context

    RSpec.shared_context "shared stuff" do
      let!(:country) do
        create :country, slug: "kw"
      end unless Country.find_by(slug: "kw").present?
    end
    

    And include it in config

    RSpec.configure do |config|
      config.include_context "shared stuff"
    end