Rspec - config.before(:suite) not running in spec_helper

Viewed 268

I'm currently looking to set up a hash in memory that can be used across my entire suite I am looking to do the following

RSpec.configure do |config|
  config.before(:suite) { $user_tokens = initialize_my_stuff }
end

However, when I go to run my suite, I get an error from one of my specs with this error: NoMethodError: undefined method 'each' for nil:NilClass

It's trying to run this:

$user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

If I comment out this spec, the before(:suite) runs as expected.

Is there a way I can ensure that the before(:suite) block runs before attempting to do anything with the specs?

1 Answers

Here's what happens:

config.before(:suite) { $user_tokens = initialize_my_stuff }

It Will be run before suite (not surprisingly), but...

$user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

..is just the spec definition, happening way before actual suite execution.

In other words:

  describe 'foo bar' do
    ...
  end

is just a bunch of blocks saved to execute later. And your $user_tokens has not been initialized yet.

What I'd suggest is to use initialize_my_stuff inside your specs like this:

initialize_my_stuff.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

Or, if it's super expensive, memorize it:

def user_tokens
  @user_tokens ||= initialize_my_stuff
end

and use it

user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end
Related