加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在不破坏FactoryGirl的情况下将seeds.rb加

发布时间:2020-12-17 01:49:41 所属栏目:百科 来源:网络整理
导读:我尝试从底部列出的SO问题中获得解决方案,但我的问题是我使用的是Capybara和FactoryGirl,我似乎无法从任何地方加载seeds.rb而不会导致许多与种子数据完全分开的测试. 大多数错误消息都是page.should_not has_content user.email上的变体 在测试之后,我尝试删
我尝试从底部列出的SO问题中获得解决方案,但我的问题是我使用的是Capybara和FactoryGirl,我似乎无法从任何地方加载seeds.rb而不会导致许多与种子数据完全分开的测试.
大多数错误消息都是page.should_not has_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中的管理员用户链接在一起
一种可能性就是在我的种子中调用一个工厂.rb来填充这些数据,但我还没弄清楚如何.

seeds.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_helper.rb

RSpec.configure do |config|
  config.before(:suite) do
    require "#{Rails.root}/db/seeds.rb"
  end
  ........
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读