这是让您认为自己要发疯的那些之一...
我有一个类 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">
怎么回事?