Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an admin role with Factory girl?

Ok so i want to test out features that need an admin user and i am trying to login as admin but in order to do that i need to have an admin user

here is my code

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

FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    email  "[email protected]"
  end

  factory :role do
    name "Admin"
  end
end

how do i connect them I tried user.roles << user_role but got this error

/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)

Here is my models

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
like image 226
Matt Elhotiby Avatar asked Feb 20 '23 20:02

Matt Elhotiby


1 Answers

spec/factories/user.rb

FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    email "[email protected]"
  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
like image 100
Marlin Pierce Avatar answered Mar 06 '23 03:03

Marlin Pierce