gpt4 book ai didi

ruby-on-rails - 如何使用 Factory girl 创建管理员角色?

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:09 25 4
gpt4 key购买 nike

好的,所以我想测试需要管理员用户的功能,我正在尝试以管理员身份登录,但为了做到这一点,我需要有一个管理员用户

这是我的代码

  let(:user) { FactoryGirl.create(:user) }
let(:admin_role) { FactoryGirl.create(:role) }

FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
email "john@doe.com"
end

factory :role do
name "Admin"
end
end

我如何连接它们我试过user.roles << user_role但是得到了这个错误

/Users/matt/Sites/application/spec/controllers/directory_controller_spec.rb:16:in `block (3 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x007fa550890d80> (NameError)

这是我的模型

class User < ActiveRecord::Base
has_many :roles, :through => :role_users
has_many :role_users
...

class Role < ActiveRecord::Base
has_many :users, :through => :role_users
has_many :role_users
...

class RoleUser < ActiveRecord::Base
belongs_to :role
belongs_to :user
end

最佳答案

spec/factories/user.rb

FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
email "john@doe.com"
end

factory :admin_user, :parent => :user do
roles { [ FactoryGirl.create(:admin_role) ] }
end

factory :role do
name { "Role_#{rand(9999)}" }
end

factory :admin_role, :parent => :role do
name "Admin"
end
end

关于ruby-on-rails - 如何使用 Factory girl 创建管理员角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com