"warning: already initialized constant" in spec_helper.rb

2.5k Views Asked by At

We have a rather large test suite that no one has used in a while, and while trying to get back to testing I keep encountering this when running bundle exec rspec spec/controllers/test_spec.rb:

spec/spec_helper.rb:82: warning: already initialized constant THIS_ID
spec/spec_helper.rb:83: warning: already initialized constant THAT_ID
spec/spec_helper.rb:84: warning: already initialized constant RANDOM_ID

And no tests are completed. This same error appears on every rspec test file I try. However, when I disable Spork, everything runs fine (all the tests fail, but they haven't been touched in a long time).

Part of my spec_helper.rb is

Spork.each_run do
  # This code will be run each time you run your specs.
  FactoryGirl.reload
  Department.where(name: ['This', 'That', 'Random']).destroy_all
  FactoryGirl.create(:department, name: 'This')
  FactoryGirl.create(:department, name: 'That')
  FactoryGirl.create(:department, name: 'Random')
  THIS_ID = Department.where(name: 'This').first.id
  THAT_ID = Department.where(name: 'That').first.id
  RANDOM_ID = Department.where(name: 'Random').first.id
end

We use Spork, FactoryGirl among other things.

Obviously I obfuscated the variable names.

1

There are 1 best solutions below

0
Zhomart On

Try using global variables instead of constants. Even better, try to put initializers inside before

describe Something do
  before do
    @this_id = Department.where(name: 'This').first.id
    @that_id = Department.where(name: 'That').first.id
    @random_id = Department.where(name: 'Random').first.id
  end
end