NameError: uninitialized constant Shoulda
Asked Answered
M

1

6

I do this tutorial https://www.digitalocean.com/community/tutorials/build-a-restful-json-api-with-rails-5-part-one

But when running the RSpec test at the chapter Models, I get the following error.

C:\Users\NCH-Lap10\Desktop\rubyprojects\todos-api>bundle exec rspec

An error occurred while loading ./spec/controllers/items_controller_spec.rb.
Failure/Error:
  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end

NameError:
  uninitialized constant Shoulda
# ./spec/rails_helper.rb:6:in `<top (required)>'
# ./spec/controllers/items_controller_spec.rb:1:in `require'
# ./spec/controllers/items_controller_spec.rb:1:in `<top (required)>'

An error occurred while loading ./spec/controllers/todos_controller_spec.rb.
Failure/Error:
  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end

NameError:
  uninitialized constant Shoulda
# ./spec/rails_helper.rb:6:in `<top (required)>'
# ./spec/controllers/todos_controller_spec.rb:1:in `require'
# ./spec/controllers/todos_controller_spec.rb:1:in `<top (required)>'

An error occurred while loading ./spec/models/item_spec.rb.

So he does not find my tests. (I copied them from the tutorial)

My test lay in spec/models and look like:

require 'rails_helper'

# Test suite for the Item model
RSpec.describe Item, type: :model do
  # Association test
  # ensure an item record belongs to a single todo record
  it { should belong_to(:todo) }
  # Validation test
  # ensure column name is present before saving
  it { should validate_presence_of(:name) }
end

Parts of my Gemfile:

group :test do
  gem 'factory_bot_rails', '~> 4.0'
  gem 'shoulda-matchers', '~> 3.1'
  gem 'faker'
  gem 'database_cleaner'
end

Should I provide more code?

Merrymaker answered 26/1, 2021 at 8:37 Comment(0)
G
15

According to this issue on github,

You might want to add this to your spec_helper.rb:

require "shoulda/matchers"
require "shoulda/matchers/integrations/rspec"

Also, be sure that spec_helper is required in rails_helper (and rails_helper required in your test file).

Edit for future readers: Second line might be deprecated in recent Rails versions (see comments) so just don't add it

Gentianella answered 26/1, 2021 at 13:24 Comment(3)
Then I get following error: Failure/Error: require "shoulda/matchers/integrations/rspec" LoadError: cannot load such file -- shoulda/matchers/integrations/rspecMerrymaker
Just add the first line then not the second oneGentianella
Just move the block Shoulda::Matchers.configure to come next to the RSpec.configure block and that issue will be solved.Pliers

© 2022 - 2024 — McMap. All rights reserved.