如何修复rspec“未定义的方法`validate_presence_of'”错误

时间:2016-02-01 23:55:48

标签: ruby-on-rails ruby rspec

当我运行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

3 个答案:

答案 0 :(得分:1)

将此添加到您的rails_helper.rb

require 'shoulda/matchers'

如果匹配器的方法不符合您的规格。

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

答案 1 :(得分: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 :(得分:1)

如果您正在测试模型或表单(意味着您的表单通过包含 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