我已经尝试从底部列出的 SO 问题中获得解决方案,但我的问题是我使用的是 Capybara 和 FactoryGirl,我似乎无法从任何地方加载 seeds.rb 而不会导致许多与种子数据完全分开的测试从打破。
大多数错误消息都是 page.should_not have_content user.email
的变体
经过测试,我尝试删除我通过工厂创建的用户。在我加载种子数据之前,这些测试都顺利通过。
How to load db:seed data into test database automatically?
Prevent Rails test from deleting seed data
What is the best way to seed a database in Rails?
How to auto-load data in the test database before to test my application?
我有一个单独的管理员组,在 seeds.rb 中分配了管理员权限和一个管理员用户链接在一起 一种可能性是在我的 seeds.rb 中调用一个工厂来填充这些数据,但我还没有弄清楚如何。
种子.rb
User.find_or_create_by_email(email: "admin@admin.admin",
password: "admin", password_confirmation: "admin")
%w{admin supermod}.each {|w| Group.find_or_create_by_name(w)}
%w{admin mod player}.each {|w| Permission.find_or_create_by_name(w)}
g = Group.find_by_name("admin")
g.permission_id = Permission.find_by_name("admin").id
puts "failed to add admin permission to admin group" unless g.save
u = User.find_by_email("neonmd@hotmail.co.uk")
ug = UserGroup.new
ug.group_id = Group.find_by_name("admin").id
ug.user_id = u.id
puts "failed to add admin group to #{u.name}" unless u.save && ug.save
失败测试
这在我加载 seeds.rb 之前通过
it "lets you remove user from group" do
user = Factory.create(:user)
admin = admin_login
group = add_group
add_user_to_group user, group
click_link "delete_#{user.email}"
page.should_not have_content user.email
end
def admin_login
admin = Factory.build(:admin)
visit login_path
fill_in "email", :with => admin.email
fill_in "password", :with => admin.password
click_button "Log In"
return admin
end
def add_group
group = Factory.build(:group)
visit new_group_path
fill_in "group_name", :with => group.name
click_button "Submit"
return group
end
def add_user_to_group (user, group)
visit groups_path
click_link "#{group.name}_users"
fill_in "user_email", :with => user.email
click_on "Add User"
end
最佳答案
我不知道原因,但需要 seeds.rb 文件而不是在测试环境中加载它是可行的,您可以在需要它的测试中调用 seed_data。
规范/helpers.rb
def seed_data
require "#{Rails.root}/db/seeds.rb"
end
更好的解决方案
spec/spec_helper.rb
RSpec.configure do |config|
config.before(:suite) do
require "#{Rails.root}/db/seeds.rb"
end
........
end
关于ruby-on-rails - 如何在不破坏 FactoryGirl 的情况下将 seeds.rb 加载到测试数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9861075/