如何修复 rspec“未定义方法‘validate_presence_of’”错误

Rul*_*Rul 6 ruby rspec ruby-on-rails

当我运行时,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
Run Code Online (Sandbox Code Playgroud)

但如何解决呢?

这是我的 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
Run Code Online (Sandbox Code Playgroud)

这是我的模型:

class User < ActiveRecord::Base
  validates :email, presence: true
end
Run Code Online (Sandbox Code Playgroud)

还有我的用户规范:

require 'rails_helper'

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

 end
Run Code Online (Sandbox Code Playgroud)

Dat*_*att 12

检查一下你是否在.config文件中添加了配置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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅shoulda-matchers。


Sso*_*esS 5

已过时:

请考虑使用这个

将其添加到您的rails_helper.rb

require 'shoulda/matchers'
Run Code Online (Sandbox Code Playgroud)

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

请看一下这个线程。希望这可以帮助