为什么false会使validates_presence_of无效?

时间:2010-05-21 16:32:45

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

确定重现此步骤的步骤:

prompt> rails test_app
prompt> cd test_app
prompt> script/generate model event_service published:boolean

然后进入迁移并添加not null并将default发布为false:

class CreateEventServices < ActiveRecord::Migration
  def self.up
    create_table :event_services do |t|
      t.boolean :published, :null => false, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :event_services
  end
end

现在迁移您的更改并运行测试:

prompt>rake db:migrate
prompt>rake

此时您应该没有错误。现在编辑模型,以便发布validate_presence_of:

class EventService < ActiveRecord::Base
  validates_presence_of :published
end

现在编辑单元测试event_service_test.rb

require 'test_helper'

class EventServiceTest < ActiveSupport::TestCase
  test "the truth" do
    e = EventService.new
    e.published = false
    assert e.valid?
  end
end

并运行rake:

prompt>rake

您将在测试中收到错误消息。现在将e.published设置为true并重新运行测试。有用!我认为这可能与布尔字段有关,但我无法弄明白。这是rails中的错误吗?或者我做错了什么?

2 个答案:

答案 0 :(得分:102)

请参阅API docs ...

  

如果要验证是否存在布尔字段(实际值为true和false),则需要使用validates_inclusion_of:field_name,:in =&gt; [true,false]。

答案 1 :(得分:7)

validates_inclusion_of :your_field, :in => [true, false]

在测试只有布尔值被模型接受时,在1.3.0的shoulda匹配器之后的某些版本中不再有效。

相反,你应该这样做:

it { should allow_value(true).for(:your_field) }  
it { should allow_value(false).for(:your_field) }
it { should_not allow_value(nil).for(:your_field) }

您可以看到讨论here

对此有一个部分修复,现在警告您是否尝试这样做here