Search code examples
ruby-on-railsrubyunit-testingenumsfixtures

Ruby: How do you configure an enum in a fixture?


Given this class:

class User < ActiveRecord::Base

enum permission: {
    permission_user: 1,
    permission_staff: 2,
    permission_manager: 3,
    permission_admin: 4,
    permission_super_admin: 5
}

I want to create a fixture that looks like this:

testuser1:
  id: 1
  username: sam
  permission: :permission_staff

I've tried a number of variations of syntax, but haven't found something that works. the resulting user.permission is either nil or 0. I know that enum is relatively recent addition. Can this be done?


Solution

  • According to the enum docs you can refer to the enumerable through the class like this:

    User.permissions[:permission_staff]
    

    And the factories are just ruby code - so they should be able to access the value in the same way

    testuser1:
      id: 1
      username: sam
      permission:  <%= User.permissions[:permission_staff] %>