验证在Rspec的和Rails布尔值 [英] Validating boolean value in Rspec and Rails

查看:205
本文介绍了验证在Rspec的和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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆