sto usando Rails 4 enumerazioni e voglio loro testare correttamente, in modo da impostare questi test per il mio campo enum:Rails - Test validazione dei campi enum
it { should validate_inclusion_of(:category).in_array(%w[sale sale_with_tax fees lease tax_free other payroll]) }
it { should validate_inclusion_of(:type).in_array(%w[receivable payable]) }
e questo è il modello che' re la convalida:
class Invoice < ActiveRecord::Base
belongs_to :user
enum category: [:sale, :sale_with_tax, :fees, :lease, :tax_free, :other, :payroll]
enum type: [:receivable, :payable]
validates :user, presence: true
validates :issue_date, presence: true
validates :series, presence: true
validates :folio, presence: true
validates :issuing_location, presence: true
validates :payment_method, presence: true
validates :last_digits, presence: true
validates :credit_note, presence: true
validates :total, presence: true
validates :subtotal, presence: true
validates :category, presence: true
validates_inclusion_of :category, in: Invoice.categories.keys
validates :type, presence: true
validates_inclusion_of :type, in: Invoice.types.keys
end
Ma quando ho eseguito i test ottengo:
1) Invoice should ensure inclusion of type in [0, 1]
Failure/Error: it { should validate_inclusion_of(:type).in_array([0,1]) }
ArgumentError:
'123456789' is not a valid type
# ./spec/models/invoice_spec.rb:20:in `block (2 levels) in <top (required)>'
2) Invoice should ensure inclusion of category in [0, 1, 2, 3, 4, 5, 6]
Failure/Error: it { should validate_inclusion_of(:category).in_array([0,1,2,3,4,5,6]) }
ArgumentError:
'123456789' is not a valid category
# ./spec/models/invoice_spec.rb:19:in `block (2 levels) in <top (required)>'
ho anche provato con i valori di stringa negli array di prova, b io ottengo lo stesso errore e davvero non lo capisco.
Questa domanda è un duplicato di http://stackoverflow.com/questions/25597031/rails-4-enum-validation. Come afferma giustamente Albertis, "non sono sicuro che questa convalida abbia senso, dal momento che provare ad assegnare un valore non valido allo stato genera un ArgumentError" – ctc
Potrebbe non essere correlato, ma sicuramente un'interessante lettura: [Usare Enum come astrazione quando si prova] (http://craftingruby.com/posts/2015/07/07/using-enumerable-as-abstraction-when-testing.html) – onebree