单表继承与Rails中的工厂女孩

时间:2014-05-05 10:26:43

标签: ruby-on-rails rspec factory-bot single-table-inheritance

我正在使用Rails 4.0.1Capybara创建FactoryGirl个应用,但我无法让我的测试正常运行。

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

详情:

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

守则:

我的模特:

# ------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记录在测试运行时没有正确插入。更让我感到困惑的是,我可以使用相同的命令从控制台插入它们,没有任何问题。我的工厂代码在某处出错了吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

变化:

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

为:

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