Ruby on rails 为什么false使无效验证的存在?
确定复制此操作的步骤:Ruby on rails 为什么false使无效验证的存在?,ruby-on-rails,unit-testing,validation,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 PUBLISED添加为false: class CreateEventServices < ActiveRecord::Migration def self.up create_
prompt> rails test_app
prompt> cd test_app
prompt> script/generate model event_service published:boolean
然后进入迁移并将not null和default PUBLISED添加为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
此时您应该不会出现错误。现在编辑模型,以便验证发布的
class EventService < ActiveRecord::Base
validates_presence_of :published
end
然后运行rake:
prompt>rake
您将在测试中得到一个错误。现在将e.published设置为true并重新运行测试。它起作用了!我认为这可能与字段是布尔值有关,但我无法理解。这是rails中的一个bug吗?还是我做错了什么?请看
如果要验证布尔字段的存在性(其中实值为true和false),则需要使用validates\u inclusion\u of:field\u name,:in=>[true,false]
当您测试模型是否只接受布尔值时,shoulda matchers 1.3.0之后的某些版本不再适用
相反,您应该这样做:
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) }
你可以看到讨论
对此有一个部分修复程序,现在警告您如果要执行此操作,请在API中也找到。我会在几分钟内接受这个答案(它说我还不能),谢谢你的快速回复!EventServer来自哪里?(最后一个代码块)哎呀!EventServer应该是EventService。。。这只是我写的一个类。它不是rails或任何其他API的一部分。
prompt>rake
validates_inclusion_of :your_field, :in => [true, false]
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) }