【发布时间】:2014-10-08 20:06:31
【问题描述】:
大家好,我遇到了几个与我类似的问题,但似乎没有一个解决方案能解决我的问题,所以在尝试了一天半之后,我决定试试运气来发布我的问题。
我有一个在 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。
问候, 没错
【问题讨论】:
-
这个表的架构是什么样子的?特别是client_type和client_status的类型是什么?它们真的是整数吗?
-
尝试将
inclusion: { in: 0..2, :presence => true }更改为inclusion: { in: 0..2}, :presence => true -
我在一个空白项目上尝试了您的代码,但我无法重现您报告的内容。您发布的代码至少可以在 Ruby 2.0、Rails 4.1、RSpec 3.1 中正常运行。
-
听起来属性是在您的代码中自动设置的。在您的客户端模型中搜索
client_status和client_type并注意before_validation挂钩。看看潜在的二传手,甚至可能assign_attributes被覆盖了。 -
你的
puts“调试语句”在@client.should be_valid行之前和之后分别输出什么?
标签: ruby-on-rails ruby validation rspec inclusion