0

This should be a no brainer. I have a Sinatra application with RSpec and, for some reason, my validations are failing with the inclusion validation.

This is my code:

class Employee < ActiveRecord::Base
   validates :department, inclusion: { in: w%(Sales, Finance, Marketing) }
end

This is the spec file:

it 'should save a valid employee' do
  employee = Employee.new(name: 'Employee One',
                        email: 'example@gmail.com',
                        title: 'Software Engineer',
                        department: 'Sales')
  expect(employee).to be_valid
end

This test fails because the department field is not 'included in the list'. This is aggravating because it fails no matter what field I put. Errors like these are usually from something simple.

What am I missing?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106
  • Welcome to Stack Overflow. It isn't necessary, or particular desirable, to add tags to the title such as "(Sinatra, RSpec)". Instead, either rely on the tags you define for the question, or work them into the title naturally and not artificially. – the Tin Man Oct 06 '15 at 00:48

2 Answers2

2

It seems that you have a syntax error, I believe w% should be %w.

Your %w syntax is conflicting with your actual list. The %w makes commas not necessary and actually adds them to your list (which is not what you want). Remove them.

 %w(Sales, Finance, Marketing)
 => ["Sales,", "Finance,", "Marketing"] 

vs

%w(Sales Finance Marketing)
 => ["Sales", "Finance", "Marketing"] 
yez
  • 2,368
  • 9
  • 15
2

%w is a short-cut for building array of strings. I think you are trying to build an array of strings like this:

["Sales", "Finance", "Marketing"]

In that case the correct form of using %w would be:

%w(Sales Finance Marketing)

See this post for more information on %w syntax in Ruby.

Also, look at the Rails Documentation for inclusion where %w is used correctly.

So, to solve your problem, change your Employee class to look like this:

class Employee < ActiveRecord::Base
   validates :department, inclusion: { in: %w(Sales Finance Marketing) }
end
Community
  • 1
  • 1
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110