【问题标题】:rails - rspec - why does this "validates_inclusion_of :role, :in => %w[one, two, three ] }" not workrails - rspec - 为什么这个“validates_inclusion_of :role, :in => %w [one, two, three ] }”不起作用
【发布时间】:2012-07-26 17:02:33
【问题描述】:

我收到此方法不存在的错误,但这似乎相当基本,我不确定为什么会收到此错误?

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>

代码:

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 validation rspec


    【解决方案1】:

    这不再相关。 ensure_inclusion_of 已弃用,将在未来版本中删除。请参阅下一个使用 validate_inclusion_of 的答案

    我不认为 validates_inclusion_of 应该有这样的匹配器。但是,根据 shoulda-matchers 项目的 master 中可用的内容,我认为您可以这样做:

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

    【讨论】:

    • 不幸的是它没有用:it { should ensure_inclusion_of(:role).in_array(['admin', 'leader', 'user']) } 给了NoMethodError: undefined method in_array'`
    • 您使用的是什么版本的 shoulda-matchers?看起来 in_array 选项直到大约 3 个月前才添加到 master 中,因此如果您需要使用该选项,您可能需要升级。
    • 查看下一条评论:应该匹配器validate_inclusion_of
    【解决方案2】:

    应该匹配器validate_inclusion_of

    ensure_inclusion_ofis deprecated 将在下一个专业中移除 释放。

    您确定您的代码在 describe Model do 块内吗?

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多