Andrei Botalov
Andrei Botalov

Reputation: 21096

How can I get rid of already initialized constant warnings when requiring files inside env.rb?

I require some files in features/support/env.rb as:

['/helpers/*', '/pages/*', '/models/*'].each do |path|
  Dir[File.dirname(__FILE__) + path].each { |file| require file }
end

(I do it as I'd want to create test users and some other stuff before any of my tests are run.)

But it seems those files are then loaded by Cucumber using load as I get a ton of warnings like when Cucumber loads them:

/home/andrey/dev/project/features/support/models/my_class.rb:2: warning: already initialized constant MyClass::MY_CONSTANT

when scenarios start. How can I get rid of those warnings?

Upvotes: 3

Views: 1214

Answers (2)

Alexis
Alexis

Reputation: 4499

You probably can setup your helpers and models in a cucumber Before hook.

The recommended way to run a before hook only once is to use a global variable, so:

Before do 
  if !$already_required
    ['/helpers/*', '/pages/*', '/models/*'].each do |path|
      Dir[File.dirname(__FILE__) + path].each { |file| require file }
    end
    $already_required = true 
  end 
end 

(https://github.com/cucumber/cucumber/wiki/Hooks#running-a-before-hook-only-once)

Upvotes: 0

Jim Stewart
Jim Stewart

Reputation: 17323

You can wrap your code in a silence_warnings block:

silence_warnings do
  ['/helpers/*', '/pages/*', '/models/*'].each do |path|
    Dir[File.dirname(__FILE__) + path].each { |file| require file }
  end
end

There's probably a better way to to whatever it is that you're trying to do, in a way that will play nice with your test framework, but the code above should handle your immediate question.

Upvotes: 1

Related Questions