ruby-on-railsrubyvalidationrspecinclusion

Rails validation inclusion error 'not included in list'


I have a table which in a MySQL db with this model:

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

So I want the client_status and the client_type to only be numeric values between 0 and 2, here is the rspec I wrote to accommodate this:

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

This is a pretty simple test, I have presence true for both client_status and client_type so I must add those in the RSPEC, however running this rspec gives me this error message:

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

I tried this, to see what the output is:

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

I received this output:

client type is: false and status is:  .

Note: I have changed the names of the model/rspec and some of the fields so that I do not violate my companies NDA.


Solution

    1. In rails you need to divide validators by comma:
        validates :client_status, presence: true, inclusion: { in: 0..2 }
    1. It has no sense to check presence, if you check on inclusion. So you can simplify your code by simple validation:
        validates :client_status, inclusion: { in: 0..2 }