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

时间:2014-08-20 03:30:39

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

如何在测试rails中使验证包含true或false工作?

我正在使用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

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

我解决了这个代码的问题。

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