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

时间:2012-05-21 11:23:36

标签: ruby validation ruby-on-rails-3.1 inclusion

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

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

编辑fixt​​ures文件,使其不创建任何记录,然后使用bundle exec rake test:units等命令运行单元测试。此测试应该传递,因为“string”不是有效状态,因此示例对象应该从调用save返回false。这不会发生。如果从VALID_VALUES数组中取出0,则可以正常工作。有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:4)

“string”在验证之前被转换为整数(因为您的状态列是整数)

"string".to_i # => 0

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

validates :status, :presence => true, :numericality => { :only_integer => true }, :inclusion => {:in => VALID_VALUES}
顺便说一句,你可以使用#valid?或#invalid?方法而不是测试中的#save