Search code examples
ruby-on-railsruby-on-rails-4testingenumsrails-activerecord

How should I test Rails Enums?


Suppose I have a model called CreditCard. Due to some technical restrictions, it's best if the card networks are represented as an enum. My code looks something like this:

class CreditCard < ActiveRecord::Base
   enum network: [:visa, :mastercard, :amex]
end

What should be tested when using enums if anything?


Solution

  • If you use an array, you need to make sure the order will be kept:

    class CreditCard < ActiveRecord::Base
      enum network: %i[visa mastercard amex]
    end
    
    RSpec.describe CreditCard, '#status' do
      let!(:network) { %i[visa mastercard amex] }
    
      it 'has the right index' do
        network.each_with_index do |item, index|
          expect(described_class.statuses[item]).to eq index
        end
      end
    end
    

    If you use Hash the order does not matter, but the value of each key does. So, it's good to make sure that each key has the equivalent value.