首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails .枚举字段的试验验证

Rails .枚举字段的试验验证
EN

Stack Overflow用户
提问于 2015-04-21 18:17:50
回答 6查看 13.3K关注 0票数 19

我正在使用Rails 4枚举,我想正确地测试它们,所以我为我的enum字段设置了这些测试:

代码语言:javascript
复制
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]) }

这就是他们正在验证的模型:

代码语言:javascript
复制
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

但当我做测试时我得到:

代码语言:javascript
复制
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)>'

我也尝试过在测试数组中使用字符串值,但是我得到了相同的错误,我真的不明白。

EN

Stack Overflow用户

回答已采纳

发布于 2016-11-09 17:18:33

使用Shoulda匹配器,我们可以使用以下方法来测试enum

代码语言:javascript
复制
it { should define_enum_for(:type).with([:receivable, :payable]) }

it { should define_enum_for(:category).
            with(:sale, :sale_with_tax, :fees, :lease, :tax_free, :other, :payroll) }
票数 23
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29780121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档