简体   繁体   中英

How to fix rspec “undefined method `validate_presence_of'” error

When I run rspec I get this error:

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

But how can fix it?

This is my 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

This is my model:

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

And my 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

Add this to your rails_helper.rb

require 'shoulda/matchers'

Your specs are missing shoulda matcher's methods.

Please take a look to this thread . Hope this helps

Check if you have added configuration in rails_helper .

if require 'shoulda/matchers' doesn't work, add following config in spec/rails_helper.rb

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

For more information, refer shoulda-matchers .

If you're testing a model or a form (meaning that your form has model-like properties by including include ActiveModel::Model ) - specifying the type of spec file will help remove this issue, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM