5

大家好,我看到了几个与我类似的问题,但似乎没有一个解决方案可以解决我的问题,所以在尝试了一天半之后,我决定试试运气来发布我的问题。

我有一个表,它在这个模型的 MySQL 数据库中:

class Client< ActiveRecord::Base

  validates :name, :length => {:maximum => 255}, :presence => true
  validates :client_status, inclusion: { in: 0..2, :presence => true }
  validates :client_type, inclusion: { in: 0..2, :presence => true}
end

所以我希望 client_status 和 client_type 只能是 0 到 2 之间的数值,这是我写的 rspec 来适应这个:

describe Client do
  before do
    @client = Client.new
  end

  it "should allow name that is less than 255 characters" do
    long_char = 'a' *254
    @client.name = long_char
    @client.client_status = 0
    @client.client_type = 1
    @client.should be_valid
  end

end

这是一个非常简单的测试,我的 client_status 和 client_type 都存在,所以我必须在 RSPEC 中添加它们,但是运行这个 rspec 会给我这个错误消息:

got errors: Value type is not included in the list, Status is not included in the list

我试过这个,看看输出是什么:

puts "client type is: #{@client.client_type} and status is: #{@client.client_status} ."

我收到了这个输出:

client type is: false and status is:  .

感谢您阅读这篇长文,我真的希望有人能为我阐明这个问题。

注意:我已经更改了模型/rspec 的名称和一些字段,这样我就不会违反我公司的 NDA。

问候, 苏雷普

4

2 回答 2

7
  1. 在 Rails 中,您需要用逗号分隔验证器:
    验证:client_status,存在:true,包含:{ in:0..2 }
  1. 如果您检查包含,检查存在是没有意义的。因此,您可以通过简单的验证来简化代码:
    验证:client_status,包含:{ 在:0..2 }
于 2014-10-08T20:29:42.223 回答
1

我认为你应该numericality:这样使用:

validates :client_status, numericality: { only_integer: true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 2 }, :presence => true
于 2014-10-08T20:28:41.730 回答