【问题标题】:RSpec/Mongoid inheritance of defaults completely different result in test/developmentRSpec/Mongoid 继承的默认值完全不同导致测试/开发
【发布时间】:2012-11-20 10:30:04
【问题描述】:

这是让你觉得自己快要发疯的那些之一......

我有一个类 Section,以及一个从它继承的 DraftSection:

(为简洁起见)

class Section
  include Mongoid::Document

  belongs_to :site

  field :name, type: String
end

class DraftSection < Section
  field :name, type: String, default: "New Section"
end

所有简单的东西......控制台证明(再次,为简洁起见)

004 > site = Site.first
 => #<Site _id: initech, name: "INITECH"> 
005 > site.sections.build
 => #<Section _id: 1, site_id: "initech", name: nil> 
006 > site.draft_sections.build
 => #<DraftSection _id: 2, site_id: "initech", name: "New Section">

如您所见 - 草稿部分名称正确默认为“新部分”,因为它在子类中被覆盖。

现在当我运行这个规范时:

describe "#new" do
  it "should return a draft section" do
    get 'new', site_id: site.id, format: :json
    assigns(:section).should == "Something..."
  end
end

哪个测试这个控制器方法:

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 ==)

什么给了???

更新:

我认为这可能是不同环境设置的问题,所以我查看了 mongoid.yml 配置文件并在选项中看到了这一点:

# Preload all models in development, needed when models use
# inheritance. (default: false)
preload_models: true

我也将它添加到测试环境设置中,但仍然没有乐趣:(

更新 2 - 情节变厚...

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

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

WTF?

【问题讨论】:

    标签: ruby-on-rails inheritance rspec mongoid


    【解决方案1】:

    好的,没有人在听,但无论如何我都会在此处发布解决方案以供将来参考...

    由于某种原因,前段时间我有一个调试会话,这意味着我将这段代码留在了我的 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 中存在类似继承问题的谷歌用户 - 确保测试堆栈中的任何地方都没有重新加载模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多