Search code examples
ruby-on-railsrspecrspec-railsshoulda

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


i'm using Ruby on Rails 4.2.0 with rspec-rails 3.1.0 and shoulda-matchers 2.7.0

when run test i have this error

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)>'

this is my model

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

and this is my spec file

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

and this is my test group in my gemfile

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

i find the same error on shoulda-matchers repo but with different versions and it didn't work for me!! what can i do?!!


Solution

  • Please replace following code.

    it { should validates_presence_of :name }
    

    with

    it { is_expected.to validate_presence_of(:name) }
    

    I hope this will work.