Search code examples
ruby-on-railsrubynomethoderrorshoulda

What am I doing wrong in Shoulda Matchers?


In gem file I write this:

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

My rails_helper

require 'rspec/rails'
require 'shoulda/matchers'

My spec_helper

require 'rails_helper'


RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.include FactoryGirl::Syntax::Methods




  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end


  Shoulda::Matchers.configure do |config|

    config.integrate do |with|
      # Choose a test framework:
      with.test_framework :rspec

      # Choose one or more libraries:
      with.library :active_record
      with.library :active_model
      with.library :action_controller
    end
  end

And finally my test:

require 'spec_helper'
describe Person do

  it {should validate_presence_of(:identifier)}
end

And I get nomethoderror

     Failure/Error: it {should validate_presence_of(:identifier)}
 NoMethodError:
   undefined method `validate_presence_of' for #<RSpec::ExampleGroups::Person:0x007fe58d13ca20>

I simply don't get it. In other project the same way works. Here it doesn't. I have spent two days to fix this problem. Are there better alternatives of Shoulda Matchers in rails?


Solution

  • Sorry you're having trouble. You need to load Rails before you require shoulda-matchers. The gem will only make model matchers available if it can see that ActiveRecord is available; if not, then you won't get them.

    It appears that you have rails_helper and spec_helper swapped. Typically in a fresh project with rspec-rails installed, rails_helper will load Rails and then require spec_helper. I would remove both files (or move them aside so you still have them) and then re-run rails g rspec:install to regenerate them. You'll still want to add the shoulda-matchers configuration block to rails_helper as you have done, but by that point ActiveRecord (and the rest of Rails) should be loaded.