【问题标题】:"warning: already initialized constant" in spec_helper.rbspec_helper.rb 中的“警告:已初始化常量”
【发布时间】:2014-07-25 10:25:22
【问题描述】:

我们有一个相当大的测试套件,有一段时间没有人使用过,在尝试重新进行测试时,我在运行 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

并且没有完成任何测试。我尝试的每个 rspec 测试文件都会出现同样的错误。但是,当我禁用 Spork 时,一切都运行良好(所有测试都失败了,但它们已经很久没有被触及了)。

我的spec_helper.rb 的一部分是

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

我们使用 Spork、FactoryGirl 等。

显然我混淆了变量名。

【问题讨论】:

  • 这只是一个警告,并不是说这会阻止您的测试运行。
  • 我个人更喜欢存根常量而不是覆盖它。
  • Ruby 中不存在常量,它们可以随时设置、取消设置和再次设置。这就是您收到警告的原因,因为常量 THIS_ID 已经设置(或初始化)并且您再次设置它。它“违反”了常数的概念。但是,嘿,没有其他方法可以用 Ruby 做到这一点! (rubylearning.com/satishtalim/ruby_constants.html)
  • @BuckDoyle,它正在阻止测试运行。它会显示这些警告然后停止。
  • 我的意思是,我认为如果你删除了常量定义,它仍然不会运行测试。这是一个警告,而不是错误。

标签: ruby-on-rails ruby unit-testing rspec spork


【解决方案1】:

尝试使用全局变量而不是常量。更好的是,尝试将初始化程序放入 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

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 1970-01-01
    • 2011-08-29
    • 2021-07-04
    • 2011-01-02
    • 2012-10-08
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多