0
votes

I have a realy easy model. A user have a role_id which depends of a role table (id, name) with a role reference.

I want create users of any types on my rspec test, with factory girl.

My first idea is something like that

factory :role do
  name "guest"
  factory :role_admin do
    name "admin"
  end
  factory :role_supervisor do
    name "supervisor"
  end
  etc... I have a lot a different roles
end



factory :user do
  email
  password '123456'
  password_confirmation '123456'
  association :role, factory: :role

  factory :admin do
    association :role, factory: :role_admin
  end
  factory :supervisor do
    association :role, factory: :role_supervisor
  end
  etc... I have a lot a different roles
end

In my model I have a simple method :

def is(role_name) 
  return self.role.name == role_name
end

It's the correct way do to? Do I realy need to create a factory for the role? Can I make a stub for this function in factory girl for each role?

I realy new with all that test stuff, thanks.

1
Does your role table have something else than an id and a name? If no, I would recommend having a look at Single Table Inheritance, it would allow you to have a class per role.mdemolin
For the moment, there is only id and role (I need a role table because roles are associated with different model/action in other table). But my question is more relationated with factory girl implementation. The single table inheritance can help me for that?Yoann Augen
No not at all, it won't help you dry your factories, I was just recommending having a look at it in case it might suits your needs for the following development :)mdemolin
Ok thanks, could be util anywayYoann Augen

1 Answers

0
votes

Factories should reflect your models.

class User
  has_many :products
end

class Product
  belongs_to :user
end

factory :user do
  products
end

factory :product do
end

If you want to have special cases (understand roles in your case) you can define traits:

factory :user do

  traits :admin do
  end

  factory :admin_user, traits: [:admin]

end

More information on traits here.