Search code examples
ruby-on-railsrubyruby-on-rails-3validationrspec

rails - rspec - why does this "validates_inclusion_of :role, :in => %w[one, two, three ] }" not work


I'm getting an error that this method does not exist but this seems fairly basic and I'm not sure why I'm getting the error?

it { should validate_presence_of :role } # This is OK.

 Failure/Error: 
it { should validate_inclusion_of :role, :in => %w[one two three ] }
 NoMethodError:
   undefined method `validate_inclusion_of' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fad7474f9b8>

For Code:

class User < ActiveRecord::Base
  validates_presence_of :role
  validates_inclusion_of :role, :in => [one, two three]       ]

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_inclusion_of


Solution

  • This is no longer relevant. ensure_inclusion_of is deprecated and will be removed in a future release. See the next answer that uses validate_inclusion_of

    I don't think there is a shoulda matcher for validates_inclusion_of like that. However, based on what's available in master on the shoulda-matchers project, I think you can do this:

    it { should ensure_inclusion_of(:role).in_array([1,2,3]) }