Ruby on rails RSpec/Mongoid继承的默认值在测试/开发中会产生完全不同的结果

Ruby on rails RSpec/Mongoid继承的默认值在测试/开发中会产生完全不同的结果,ruby-on-rails,inheritance,rspec,mongoid,Ruby On Rails,Inheritance,Rspec,Mongoid,这是其中一个让你觉得自己疯了 我有一个类节和一个从中继承的DraftSection: (为简洁起见进行了修剪) 及 测试此控制器方法的步骤: def new @section = @site.draft_sections.build respond_with @section end 失败(如预期),但有以下情况: Failure/Error: assigns(:section).should == "Something..." expected: "Something..."

这是其中一个让你觉得自己疯了

我有一个类节和一个从中继承的DraftSection:

(为简洁起见进行了修剪)

测试此控制器方法的步骤:

def new
  @section = @site.draft_sections.build
  respond_with @section
end
失败(如预期),但有以下情况:

Failure/Error: assigns(:section).should == "Something..."
   expected: "Something..."
        got: #<DraftSection _id: 1, site_id: "site-name-4", name: nil> (using ==)
我也将其添加到测试环境设置中,但仍然没有乐趣:(

更新2-绘图变厚

我想我应该尝试在测试环境中加载控制台,并尝试与以前相同的操作:

001 > site = Site.first
 => #<Site _id: initech, name: "INITECH"> 
002 > site.draft_sections.build
 => #<DraftSection _id: 1, site_id: "initech", name: "New Section">
001>site=site.first
=> # 
002>site.draft\u sections.build
=> #

WTF?

好的,没有人在听,但我会在这里发布解决方案,以供将来参考

出于某种原因,前一段时间我有一个调试会话,这意味着我在Spork.each_run块中留下了这段代码

  # Reload all model files when run each spec
  # otherwise there might be out-of-date testing
  # require 'rspec/rails'
  Dir["#{Rails.root}/app/controllers//*.rb"].each do |controller|
    load controller
  end
  Dir["#{Rails.root}/app/models//*.rb"].each do |model|
    load model
  end
  Dir["#{Rails.root}/lib//*.rb"].each do |klass|
    load klass
  end
这导致模型在规范每次运行时都会被重新加载。毫不奇怪,这破坏了规范运行时在内存中设置类的方式

明确地解释了为什么调试如此困难

因此,对于只在Rspec中存在类似继承问题的未来谷歌用户,请确保测试堆栈中的任何地方都没有重新加载模型

def new
  @section = @site.draft_sections.build
  respond_with @section
end
Failure/Error: assigns(:section).should == "Something..."
   expected: "Something..."
        got: #<DraftSection _id: 1, site_id: "site-name-4", name: nil> (using ==)
# Preload all models in development, needed when models use
# inheritance. (default: false)
preload_models: true
001 > site = Site.first
 => #<Site _id: initech, name: "INITECH"> 
002 > site.draft_sections.build
 => #<DraftSection _id: 1, site_id: "initech", name: "New Section">
  # Reload all model files when run each spec
  # otherwise there might be out-of-date testing
  # require 'rspec/rails'
  Dir["#{Rails.root}/app/controllers//*.rb"].each do |controller|
    load controller
  end
  Dir["#{Rails.root}/app/models//*.rb"].each do |model|
    load model
  end
  Dir["#{Rails.root}/lib//*.rb"].each do |klass|
    load klass
  end