shoulda-matchers: Rails 5 undefined method `validate_presence_of`

I’m upgrading to from Rails 4.2.6 to 5.0.0 and receiving undefined method errors for all shoulda matchers. I’m using shoulda-matchers (3.1.1).

  2) Location
     Failure/Error: it { should validate_presence_of(:latitude) }

     NoMethodError:
       undefined method `validate_presence_of' for #<RSpec::ExampleGroups::Location:0x007ff81faa4de8>
     # ./spec/models/location_spec.rb:6:in `block (2 levels) in <top (required)>'
     # ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'

Edit

I managed to fix the error using the following. However, this should be handled automatically by the gem:

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 82
  • Comments: 29

Commits related to this issue

Most upvoted comments

Try this: Open your spec/rails_helper.rb file and configure shoulda-matchers to work with RSpec by pasting in the following:

require ‘shoulda/matchers’

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

source: https://www.sitepoint.com/learn-the-first-best-practices-for-rails-and-rspec/

Although it is already closed, I came across this problem when I ran a spec for an ActiveModel::Model without define type: :model in Rspec.describe block.

The code bellow code fails with undefined_method error…

RSpec.describe NewInvestment do

  context 'validations' do
    it { is_expected.to validate_presence_of(:investment_product_id) }
   end
end

…but this one works perfectly

RSpec.describe NewInvestment, type: :model do

  context 'validations' do
    it { is_expected.to validate_presence_of(:investment_product_id) }
   end
end

Install the gem shoulda-matchers

group :test do
  gem 'shoulda-matchers'
end

Write following code in the rails_helper.rb

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

Had the same issue, got it working by adding

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

as mentioned by most of the people in this thread

shoulda-matchers-4.1.2
ruby 2.5.3
rails - 5.2.3

I’m using rails 6-beta and it is still happening