Rails验证包含错误'未包含在列表中'

Sur*_*rep 5 ruby validation rspec ruby-on-rails inclusion

大家好我已经看到了几个类似于我的问题,但没有一个解决方案似乎解决了我的问题所以经过一天半的尝试,我决定尝试运气发布我的问题.

我在这个模型的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
Run Code Online (Sandbox Code Playgroud)

所以我希望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
Run Code Online (Sandbox Code Playgroud)

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

got errors: Value type is not included in the list, Status is not included in the list
Run Code Online (Sandbox Code Playgroud)

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

puts "client type is: #{@client.client_type} and status is: #{@client.client_status} ."
Run Code Online (Sandbox Code Playgroud)

我收到了这个输出:

client type is: false and status is:  .
Run Code Online (Sandbox Code Playgroud)

感谢您阅读这篇长篇文章,我真的希望有人可以为我解释这个问题.

注意:我更改了model/rspec和某些字段的名称,这样我就不会违反我公司的NDA.

此致,Surep

Ale*_*mes 6

  1. 在rails中,您需要用逗号分隔验证器:
    validates :client_status, presence: true, inclusion: { in: 0..2 }
  1. 如果检查包含,检查存在是没有意义的.因此,您可以通过简单的验证来简化代码:
    validates :client_status, inclusion: { in: 0..2 }