在Rails中使用工厂女孩进行单表继承 [英] Single Table Inheritance with Factory Girl in Rails
问题描述
我正在使用Capybara
和FactoryGirl
制作Rails 4.0.1
应用程序,但是我无法使我的测试正常工作.
I'm making a Rails 4.0.1
app using Capybara
and FactoryGirl
but I'm having trouble getting my tests to work correctly.
我正在使用单表继承来制作Collection < ActiveRecord::Base
和VideoCollection < Collection
模型.在我的测试中使用Factory Girl时,模型似乎没有得到应有的实例化.
I'm using single table inheritance to make a Collection < ActiveRecord::Base
and a VideoCollection < Collection
model. When using Factory Girl in my tests, the models don't seem to get instantiated as they should.
- 当我在浏览器中目视检查正在测试的视图时,它会正确显示该集合.
- 当我在测试中为同一视图运行
print page.html
时,该集合未出现在页面代码中. - 如果我使用
rails c test
进入测试控制台并执行FactoryGirl.create(:video_collection)
,那么视频集就可以插入数据库了.
- When I visually inspect a view in my browser that I'm testing, it displays the collection properly.
- When I run
print page.html
in the test for the same view, the collection doesn't appear in the page code. - If I go into the test console with
rails c test
and executeFactoryGirl.create(:video_collection)
, then the video collections gets inserted into the database no problem.
我的模特:
# ------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记录未正确插入.令我感到困惑的是,我可以使用相同的命令从控制台中毫无问题地插入它们.我的工厂代码是否存在错误?
I don't understand why the video_collection records from the factory aren't getting inserted properly when the test runs. It's even more baffling to me that fact that I can insert them from the console with the same command with no problem. Is there an error in my factory code somewhere?
感谢您的帮助!
推荐答案
更改:
let(:video_collection) do
FactoryGirl.create(:video_collection)
end
收件人:
let!(:video_collection) do
FactoryGirl.create(:video_collection)
end
这篇关于在Rails中使用工厂女孩进行单表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!