Thomas Deranek
Thomas Deranek

Reputation: 353

RSpec error: Uninitialized constant ModuleName::Chef (NameError)

I am getting an error when trying to write an RSpec test for my class.

The relevant class code is as follows (class_name.rb):

module ModuleName
  class ClassName < Chef::Knife
  ...
end

My relevant RSpec code is as follows: (class_name_spec.rb):

require 'spec_helper'
RSpec.describe ModuleName::ClassName do
  ...
end

And my spec_helper.rb is as follows:

require 'rspec'
require 'chef/knife/class_name'

The error that results is as follows

C:/.../project_folder/lib/chef/knife/class_name.rb:2:in '<module:ModuleName>': uninitialized constant ModuleName::Chef (NameError)

The code is a working code base that I am writing tests for so I don't believe it is a problem with the code in class_name. Am I missing an include statement in my class_name_spec.rb file? Or is there something wrong with the way I set this up?

Thanks in advance!

Upvotes: 1

Views: 2001

Answers (2)

Thomas Deranek
Thomas Deranek

Reputation: 353

I solved this issue.

It turns out that I needed to modify my spec_helper to be as follows:

require 'rspec'
require 'chef/knife'
require 'chef/knife/class_name'

This confused me because I don't have any other files in the 'chef/knife' folder, but as it turns out that is just how ruby accesses the knife part of the chef gem. If anyone else has something to add that would further enlighten me, please do. I am still sort of confused about it

Upvotes: 1

DiegoSalazar
DiegoSalazar

Reputation: 13521

Things to check in solving your issue:

Make sure the Chef gem is in the :test gem group in your Gemfile (so that it loads when running specs). It should be in group :development, :test. Then...

Change this line:

class ClassName < Chef::Knife

to:

class ClassName < ::Chef::Knife

That says to look for Chef in the root namespace rather than in ModuleName.

Upvotes: 0

Related Questions