单表inheritance与Rails中的工厂女孩

我正在使用FactoryGirlFactoryGirl制作Rails 4.0.1应用程序,但我无法让我的测试正常工作。

我正在使用单表inheritance来创建Collection < ActiveRecord::BaseVideoCollection < Collection模型。 在我的测试中使用Factory Girl时,模型似乎没有像他们应该那样实例化。

细节:

  • 当我在浏览器中直观地检查我正在测试的视图时,它会正确显示集合。
  • 当我在测试中为同一视图运行print page.html时,该集合不会出现在页面代码中。
  • 如果我使用rails c test进入测试控制台并执行FactoryGirl.create(:video_collection) ,那么video集合就会插入到数据库中没问题。

代码:

我的模特:

 # ------in app/models/collection.rb------ class Collection < ActiveRecord::Base end # ------in app/models/video_collection.rb------ class VideoCollection < Collection end # ------in db/schema.rb------ create_table "collections", force: true do |t| t.string "type" t.datetime "created_at" t.datetime "updated_at" t.string "name" t.string "tile_image_link" end 

我的工厂:

 FactoryGirl.define do ... factory :collection do |collection| factory :video_collection, class: VideoCollection, parent: :collection do |u| u.sequence(:name) { |n| "Video Collection #{n}" } tile_image_link "some-link.png" type "VideoCollection" end end ... end 

我的测试:

 # -----in spec/requests/video_collections_spec.rb----- require 'spec_helper' describe "VideoCollections" do let(:video_collection) do FactoryGirl.create(:video_collection) end ... ### This test fails ### expect(page).to have_link(video_collection.name, href: "video/#{video_collection.id}") 

测试输出:

 Failure/Error: expect(page).to have_link(video_collection.name, expected #has_link?("Video Collection 1", {:href=>"video/181"}) to return true, got false 

我不明白为什么测试运行时工厂的video_collection记录没有正确插入。 更让我感到困惑的是,我可以使用相同的命令从控制台插入它们,没有任何问题。 我的工厂代码在某处出错了吗?

谢谢您的帮助!

更改:

 let(:video_collection) do FactoryGirl.create(:video_collection) end 

至:

 let!(:video_collection) do FactoryGirl.create(:video_collection) end