ruby-on-rails - 如何在不破坏 FactoryGirl 的情况下将 seeds.rb 加载到测试数据库中?

标签 ruby-on-rails testing factory-bot

我已经尝试从底部列出的 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/

相关文章:

ruby-on-rails - Heroku 上的免费 SSL 安全证书?

testing - Backbone - View 中使用 ReadFile 的测试方法

silverlight - 两个应用程序(桌面和移动)之间的软件测试

ruby-on-rails - RSpec + FactoryGirl 和 Controller 规范

ruby-on-rails - 适用于 Ruby on Rails 的 Facebook 营销 API(广告)

ruby-on-rails - 如何开发 gem ?

ruby-on-rails - 安装mysql gem时出错

android - 有没有办法使用 espresso 来测试 View 的大小(高度和宽度)以进行 android Instrumentation 测试?

ruby-on-rails - 与工厂机器人创建/构建冲突的种子数据库键值

ruby-on-rails - Rspec/FactoryGirl : changes in factory not saving in test database?