【发布时间】:2014-05-05 10:26:42
【问题描述】:
我正在使用Capybara 和FactoryGirl 制作Rails 4.0.1 应用程序,但我无法让我的测试正常工作。
我正在使用单表继承来创建 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 记录没有正确插入。更令我困惑的是,我可以使用相同的命令从控制台毫无问题地插入它们。我的工厂代码是否有错误?
感谢您的帮助!
【问题讨论】:
-
我喜欢rspec,将等待另一个问题:)
标签: ruby-on-rails rspec factory-bot single-table-inheritance