简体   繁体   中英

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?

If you use array, you need to make sure the order will be keeped:

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

describe CreditCard, '#status' do
  let(:network) { [: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, will. So, it's always good to the to make sure the same number for each key.

According to Rails doc for Enum every value of the array correspond to an integer. I'm guessing you want to test that the network array always keeps its same order. If you're using rspec, you can do something like:

describe 'CreditCard' do
  let(:network_values) do
    { visa: 0,
      master: 1
      # etc
    }
  end
  subject { described_class.new }

  it 'has valid a network' do 
    network_values.each do |type, value|
      subject.network = value
      subject.save 
      expect(subject.network).to eql(type.to_s)
    end 
  end 
end 

ps: I'm writing from my mobile phone maybe you'll need some tweaking to run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM