验证在Rspec的和Rails布尔值 [英] Validating boolean value in Rspec and Rails
问题描述
我是pretty的困惑如何在Rspec的和Rails验证布尔值。我明白了一切,除了假
和零
被当作真
在Ruby中。但是,当我使用MySQL和Rails,它使用了 1
为真
和 0
为假
(如果我的理解是正确的)。
I'm pretty confused how to validate boolean values in Rspec and Rails. I understand everything except for false
and nil
are taken as true
in Ruby. But when I use MySQL with Rails, it uses 1
for true
and 0
for false
(if my understanding is correct).
我有以下的模型规范。我想测试超级用户
属性布尔值。
I have the following model spec. I'd like to test boolean value for superuser
attribute.
- 如何写规格在这里?
- 我怎么能写在这里实现code?
-
是我的规格和执行code具体到特定的数据库(如MySQL和PostgreSQL)?
- How can I write specs here?
- How can I write implementation code here?
Are my specs and implementation code specific to a specific database (like MySQL and PostgreSQL)?
require 'spec_helper'
describe User do
before(:each) do
@valid_attributes = {
:username => "mike",
:password => "super_encryped_password",
:email => "mike@example.com",
:superuser => true
}
end
it "should create a new instance given valid attributes" do
User.create!(@valid_attributes)
end
it "should have true or false for superuser" do
@valid_attributes[:superuser] = "hello"
User.new(@valid_attributes).should have(1).error_on(:superuser)
end
end
推荐答案
一个重要的事情是,ActiveRecord的类型转换是否在幕后,所以你不必担心如何将数据库存储布尔值。你甚至不需要验证一个字段是布尔值,只要你设置该字段为布尔时preparing迁移。您可能希望确保字段不为零
不过,有一个 validates_ presence_of:超级用户
声明模型类。
One important thing is that ActiveRecord does typecasting behind the scenes, so you do not have to worry about how your database stores boolean values. You even need not validate that a field is boolean, as long as you set that field as boolean when preparing your migration. You may want to make sure the field is not nil
though, with a validates_presence_of :superuser
declaration in your model class.
这篇关于验证在Rspec的和Rails布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!