【问题标题】:Ruby on Rails 4.2.0 with rspec-rails 3.1.0 and shoulda-matchers 2.7.0 undefined method `validates_presence_of' for带有 rspec-rails 3.1.0 和 shoulda-matchers 2.7.0 的 Ruby on Rails 4.2.0 未定义方法“validates_presence_of”
【发布时间】:2015-03-17 11:23:28
【问题描述】:

我正在使用 Ruby on Rails 4.2.0rspec-rails 3.1.0should-matchers 2.7.0 p>

运行测试时出现此错误

Failure/Error: it { should validates_presence_of :name }
     NoMethodError:
       undefined method `validates_presence_of' for #<RSpec::ExampleGroups::Profile::Vaidations:0x00000007881768>
     # ./spec/models/profile_spec.rb:5:in `block (3 levels) in <top (required)>'

这是我的模特

class Profile < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
  validates :user, presence: true
  validates :username, presence: true, uniqueness: { case_sensitive: false }, length: {maximum: 50}
  validates :name, presence: true, length: {maximum: 50}
  validates :phone, presence: true, uniqueness: { case_sensitive: false }, length: {maximum: 50}
  validates :age, presence: true, length: {maximum: 4}
end

这是我的规范文件

require 'rails_helper'
describe Profile do
  describe "vaidations" do
    it { should validates_presence_of :name }

    it { should validates_presence_of :age }
    it { should validates_numericality_of :age }

    it { should validates_presence_of :phone }
    it { should validates_uniqueness_of :phone }

    it { should validates_presence_of :username }
    it { should validates_uniqueness_of :username }
  end

  describe 'association' do
    it { should belongs_to :user }
  end
end

这是我的 gemfile 中的测试组

group :test do
  gem 'rspec-rails'
  gem 'shoulda-matchers', require: false
  gem 'factory_girl_rails'
end

我在 shoulda-matchers repo 上发现了同样的错误,但版本不同,它对我不起作用!! 我该怎么办?!!

【问题讨论】:

  • 你试过这个it { is_expected.to validate_presence_of(:name) } 吗?
  • 尝试添加:describe Profile, type: :model do
  • 感谢@AmitSharma,它工作正常:D
  • @AdhamEl-Deeb 您在其他领域遇到什么错误?

标签: ruby-on-rails rspec rspec-rails shoulda


【解决方案1】:

而不是它 它 { 应该 validates_presence_of :name }it { 应该 validate_presence_of :name }

【讨论】:

    【解决方案2】:
    .....
     it { should validate_presence_of :name }
    .....
    

    您必须从所有字符串中的“validateS_presence_of”中删除字符“S”

    【讨论】:

      【解决方案3】:

      请替换以下代码。

      it { should validates_presence_of :name }
      

      it { is_expected.to validate_presence_of(:name) }
      

      我希望这会奏效。

      【讨论】:

      • 它可以与 it { validate_presence_of(:name) } 一起使用,而没有 is_expected.to 问题是 validates 中的“s” 它是 validate 只有没有“s”
      • it { validate_presence_of(:name) } 没有做任何事情:它实例化了 validate_presence_of 匹配器,但没有在期望中使用它,因此示例将通过,但它也永远不会失败.
      猜你喜欢
      • 2016-08-22
      • 2016-03-13
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多