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

标签 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.6.2 版本下,should-matchers 在测试 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.

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

关于ruby-on-rails - 如何在测试 rails 中验证包含 true 或 false 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25396297/

相关文章:

mysql - 在 Rails 脚手架的日期范围内显示数据

ruby-on-rails - 在 rails 上运行 cron 作业(部署在多个服务器上)

ruby-on-rails - 在 Facebook 页面上发布的简单方法(不是个人资料,而是粉丝专页)

ruby-on-rails - RSpec - 未定义的方法 `key?'

ruby-on-rails - CarrierWave - 仅删除版本,而非原始版本

带有类型丰富的 Scala 测试

php - 为 PHPUnit 配置文件名

c++ - 没有匹配的构造函数来初始化 Mock Factory

ruby-on-rails - 如何使用 Shoulda 正确测试此 Controller 操作?

ruby-on-rails - 困惑 - spec_helper.rb :94:in `<top (required)>' : uninitialized constant Shoulda (NameError)