【问题标题】:How to fix rspec "undefined method `validate_presence_of'" error如何修复 rspec“未定义的方法 `validate_presence_of'”错误
【发布时间】:2016-02-01 23:55:48
【问题描述】:

当我运行 rspec 时,我收到此错误:

Failures:

  1) User
    Failure/Error: it { should validate_presence_of :email  }

  NoMethodError:
      undefined method `validate_presence_of' for <RSpec::ExampleGroups::User:0x007f8177ff3408>
    # ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.00168 seconds (files took 2.72 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:5 # User

但是如何解决呢?

这是我的 Gemfile:

group :development, :test do
 gem 'byebug'
 gem 'rspec-rails', '~> 3.4', '>= 3.4.1'
 gem "factory_girl_rails", "~> 4.0"
 gem 'capybara', '~> 2.6', '>= 2.6.2'
 # Call 'byebug' anywhere in the code to stop execution and get a       debugger console
gem 'byebug'
end

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

这是我的模型:

class User < ActiveRecord::Base
  validates :email, presence: true
end

还有我的 user_spec:

require 'rails_helper'

 RSpec.describe User, type: :model do
   #pending "add some examples to (or delete) #{__FILE__}"
   it { should validate_presence_of :email  }   

 end

【问题讨论】:

标签: ruby-on-rails ruby rspec


【解决方案1】:

检查您是否在rails_helper 中添加了配置。

如果require 'shoulda/matchers'不起作用,请在spec/rails_helper.rb中添加以下配置

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

更多信息,请参考shoulda-matchers

【讨论】:

    【解决方案2】:

    过时:

    请考虑使用this

    将此添加到您的 rails_helper.rb

    require 'shoulda/matchers'
    

    您的规范缺少匹配器的方法。

    请查看此thread。希望这会有所帮助

    【讨论】:

    • 谢谢你在 shoulda_matchers_helper.rb 中单独添加这个: shoulda::Matchers.configure do |config| config.integrate 做 |with| with.test_framework :rspec with.library :rails end end
    • 已经不行了,请考虑使用stackoverflow.com/a/61292450/1240330
    【解决方案3】:

    如果您正在测试模型或表单(意味着您的表单通过包含 include ActiveModel::Model 具有类似模型的属性) - 指定规范文件的类型将有助于消除此问题,即 type: :model

    RSpec.describe TestForm, type: :model do
      subject { described_class.new(user_id) }
      let(:user_id) { 1 }
    
      it { is_expected.to validate_presence_of(:whatever) }
    end
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多