代码之家  ›  专栏  ›  技术社区  ›  tardjo

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

  •  2
  • tardjo  · 技术社区  · 11 年前

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

    我在用宝石 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
    

    如何解决这个问题?

    2 回复  |  直到 11 年前
        1
  •  3
  •   infused    11 年前

    在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.
    

    似乎您应该删除测试和验证。

        2
  •  2
  •   Thadeu Esteves Jr.    9 年前

    我用类似的代码解决了问题。

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