Tôi đang sử dụng Rails 4 enums và tôi muốn đúng cách kiểm tra chúng, vì vậy tôi thiết lập các bài kiểm tra lên cho các lĩnh vực enum của tôi:Rails - xác nhận thử nghiệm lĩnh vực 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]) }
Và đây là mô hình họ tái xác nhận:
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
Nhưng khi tôi chạy thử nghiệm tôi nhận được:
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)>'
tôi cũng đã thử với các giá trị chuỗi trong mảng kiểm tra, b Tôi nhận được cùng một lỗi và tôi thực sự không hiểu nó.
Câu hỏi này là một bản sao của http://stackoverflow.com/questions/25597031/rails-4-enum-validation. Như Albertis nói đúng, "Tôi không chắc rằng việc xác thực này có ý nghĩa, vì cố gắng gán giá trị không hợp lệ cho trạng thái làm tăng một ArgumentError" – ctc
Có thể không liên quan, nhưng chắc chắn là một điều thú vị: [Sử dụng Enum như trừu tượng khi thử nghiệm] (http://craftingruby.com/posts/2015/07/07/using-enumerable-as-abstraction-when-testing.html) – onebree