-
Notifications
You must be signed in to change notification settings - Fork 405
Rolify with Rails fixtures
Muhammad edited this page Feb 3, 2020
·
4 revisions
Below are two ways of getting rolify to work with rails fixtures. Explaining Rails fixtures is outside the scope of this wiki. For more information please see rails fixture documentation.
Method 1: The following solution works for Rails 4.2 and assumes roles are attached to a User
model. To get rolify working with Rails fixtures:
# pretty much exclusively created for our fixtures to work
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
# users.yml
some_user:
# roles.yml - key here is to NOT include "resource"
admin_role:
name: :admin
# users_roles.yml
users_roles1:
user: some_user
role: admin
# in some test file
fixtures :users, :roles, :users_roles
users(:some_user).has_role? :admin # => true
Method 2: If you feel nervous about adding a rails model strictly for supporting fixtures there is an alternative solution. The key here is to not define users
in roles.yml fixtures since doing so will prevent attributes from being set correctly.
example:
# roles.yml
first_dealership_admin_role:
name: :dealership_admin
resource_id: 1
resource_type: 'Dealership'
# users.yml
dealership_admin:
id: 4
email: '[email protected]'
encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
dealership_id: 1
roles: first_dealership_admin_role
# dealerships.yml
one:
id: 1
name: dealership_name