我正在使用Rails 4.0.1
和Capybara
创建FactoryGirl
个应用,但我无法让我的测试正常运行。
我使用单表继承来制作Collection < ActiveRecord::Base
和VideoCollection < 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记录在测试运行时没有正确插入。更让我感到困惑的是,我可以使用相同的命令从控制台插入它们,没有任何问题。我的工厂代码在某处出错了吗?
感谢您的帮助!
答案 0 :(得分:2)
变化:
let(:video_collection) do
FactoryGirl.create(:video_collection)
end
为:
let!(:video_collection) do
FactoryGirl.create(:video_collection)
end