Ruby on Rails 4.2.0 with rspec-rails 3.1.0 and shoulda-matchers 2.7.0 undefined method `validates_presence_of' for

Ruby on Rails 4.2.0 with rspec-rails 3.1.0 and shoulda-matchers 2.7.0 undefined method `validates_presence_of' for

我在 Rails 4.2.0 上使用 Ruby 和 rspec-rails 3.1.0 应该匹配 2.7.0

当运行测试时我有这个错误

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 { should validates_presence_of :name }

it { is_expected.to validate_presence_of(:name) }

我希望这会奏效。

.....
 it { should validate_presence_of :name }
.....

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

取而代之 它{ 应该 validates_presence_of :name }它 { 应该 validate_presence_of :name }