Winston Kotzan
Winston Kotzan

Reputation: 2087

Setting a variable once for each time rspec is run

I am writing a Ruby gem that accesses the features of a web based API. I need to set up an object which will be initialized and log into the API just once for each time the tests are run. before(:all) is still excessive because it will run once for every describe block, and what I want is something that universally sets up once for all of the test files.

UPDATE

Just as a follow up, to make the object I was using available in the tests, I had to add a setting to the rspec config like this

config.add_setting :client
config.before(:suite) do
  RSpec.configuration.client = TDAmeritradeApi::Client.new
  RSpec.configuration.client.login
end

And then in the describe blocks I do this:

let(:client) { RSpec.configuration.client }

Upvotes: 1

Views: 949

Answers (2)

Alex Peachey
Alex Peachey

Reputation: 4686

I believe you are looking for before(:suite) and you can use it in the config section of your spec_helper.rb.

RSpec.configure do |config|
  config.before(:suite) do
    # API login
  end
end

Upvotes: 2

mvidaurre
mvidaurre

Reputation: 489

You can use before(:suite) to run a block of code before any example groups are run. This should be declared in RSpec.configure

Source: http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks

Upvotes: 1

Related Questions