Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
sunnyrjuneja Avatar asked Dec 24 '22 20:12

sunnyrjuneja


1 Answers

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.

like image 124
Washington Botelho Avatar answered Jan 05 '23 08:01

Washington Botelho