Set variable once for all examples in RSpec suite (without using a global variable)

Viewed 3543

What is the conventional way to set a variable once to be used by all examples in an RSpec suite?

I currently set a global variable in spec_helper that checks whether the specs are being run in a "debug mode"

$debug = ENV.key?('DEBUG') && (ENV['DEBUG'].casecmp('false') != 0) && (ENV['DEBUG'].casecmp('no') != 0)

How do I make this information available to all the examples in the suite without using a global variable and without re-computing the value for each context and/or example? (My understanding is that using a before(:all) block would re-compute it once per context; but, that before(:suite) can't be used to set instance variables.)

(Note: I'm asking more to learn about good design that to address this specific problem. I know one global isn't a big deal.)

2 Answers

There is an easy way to keep all the setup stuff in spec_helper.rb, including custom variables, and access those variables in tests. The following is modified from the RSpec-core 3.10 docs, and is not Rails-specific.

Create a new setting for RSpec.configure called my_variable, and give it a value, like this:

# spec/spec_helper.rb

RSpec.configure do |config|
  config.add_setting :my_variable
  config.my_variable = "Value of my_variable"
end

Access settings as a new read-only property in RSpec.configuration from your test:

# spec/my_spec.rb

RSpec.describe(MyModule) do
  it "creates an instance of something" do
    my_instance = MyModule::MyClass.new(RSpec.configuration.my_variable)
  end
end
Related