【问题标题】:how to make validates inclusion true or false work in testing rails?如何在测试rails中使验证包含真或假工作?
【发布时间】:2014-08-20 03:30:38
【问题描述】:

如何在测试 rails 中验证包含真或假?

我正在使用 gem shoulda 进行测试,如果我的模型中有这样的验证:

class Draw < ActiveRecord::Base    
    validates :available, inclusion: { in: [true, false] }
end

当我在模型测试中尝试此代码时,如何使此验证工作在测试中:

require 'test_helper'

class DrawTest < ActiveSupport::TestCase    
  should ensure_inclusion_of(:available).in_array([true, false])
end

我得到这样的错误:

DrawTest#test_: Draw should ensure inclusion of available in [true, false].  [/home/my_user/.rvm/gems/ruby-2.0.0-p451/gems/shoulda-context-1.2.1/lib/shoulda/context/context.rb:344]:
[true, false] doesn't match array in validation

如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails unit-testing shoulda model-validation


    【解决方案1】:

    在 2.6.2 版本下,应该匹配器在测试 ensure_inclusion_of(:available).in_array([true, false]) 时发出以下警告:

    Warning from shoulda-matchers:
    
    You are using `ensure_inclusion_of` to assert that a boolean column allows
    boolean values and disallows non-boolean ones. Assuming you are using
    `validates_format_of` in your model, be aware that it is not possible to fully
    test this, and in fact the validation is superfluous, as boolean columns will
    automatically convert non-boolean values to boolean ones. Hence, you should
    consider removing this test and the corresponding validation.
    

    看来您应该只删除测试和验证。

    【讨论】:

    • 在将 should-matchers 更新到 2.6.0 版后,我仍然收到错误 @infused ?
    • 你用的是什么版本?
    • should (3.5.0), shoulda-context (1.2.1, 1.1.6) and shoulda-matchers (2.6.2, 2.6.0)
    • @tardjo,根据更新的信息,您应该删除测试和验证。
    【解决方案2】:

    我用这样的代码解决了问题。

    it { should allow_value(%w(true false)).for(:done) }

    【讨论】:

    • 此测试不检查:done 字段是否可以接受数组,将被视为true
    猜你喜欢
    • 2011-11-16
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 2021-07-09
    相关资源
    最近更新 更多