为什么这个 Rails 包含验证失败



顺便说一下,使用 Rails 3.1.1。要重现这一点,请创建一个新的 Rails 项目。在此项目中创建一个名为"示例"的新模型。为此模型创建如下所示的迁移...

class CreateExamples < ActiveRecord::Migration
    def change
        create_table :examples do |t|
            t.integer :status, :null => false
            t.timestamps
        end
    end
end

让示例模型代码如下所示...

class Example < ActiveRecord::Base
    VALID_VALUES = [0, 1, 2, 3]
    validates :status, :presence => true, :inclusion => {:in => VALID_VALUES}
end

现在编辑此模型的单元测试并向其添加以下代码...

require 'test_helper'
class ExampleTest < ActiveSupport::TestCase
    test "whats going on here" do
        example = Example.new(:status => "string")
        assert !example.save
    end
end

编辑夹具文件,使其不创建任何记录,然后使用诸如 bundle exec rake test:units 之类的命令运行单元测试。此测试应通过,因为"string"不是有效状态,因此示例对象应从调用中返回 false 以保存。这并没有发生。如果您从VALID_VALUES数组中取出 0,那么这就可以了。有人知道为什么会这样吗?

"string" 在验证之前被强制转换为整数(因为您的状态列是整数(

"string".to_i # => 0

您可以使用数值验证器来避免这种情况:

validates :status, :presence => true, :numericality => { :only_integer => true }, :inclusion => {:in => VALID_VALUES}

顺便说一句,您可以在测试中使用 #valid?或 #invalid?方法而不是 #save

最新更新