简体   繁体   中英

NameError: unitialized constant ServiceName with default rspec configuration

I created rails new --api whatever with:

gem 'rspec-rails', '~> 3.8'

in my Gemfile . Then, I created:

app/services/whatever_module/whatever_class.rb

and corresponding spec file:

spec/services/whatever_module/whatever_class_spec.rb 

Now, when I run:

rspec services

I get this error:

NameError: uninitialized constant WhateverModule

How do I tell rspec to recognize the module by its spec path?

Your spec file should be in

spec/services/distamce/whatever_class_spec.rb .

In you case rspec tries to find the WhateverModule because of /whatever_module/ in your pathing for the spec file. You can try this to change to spec/services/foo_bar/whatever_class_spec.rb and you will get the missing FooBarModule error.

I think I figured out what you missed.

Rspec does not automatically require your app folder and so there are no modules or classes available from the app folder initially.

When you check https://github.com/rspec/rspec-rails#installation @2 then you can see you have to add some boilerplate files for rspec like rails_helper.rb and spec_helper.rb with rails generate rspec:install . These are responsible for all rspec related settings and the require of the app folder.

Also its required to add require 'rails_helper' on top of each spec file.

After you have done all this and you get the error Unable to autoload constant WhateverModule::WhateverClass then your whatever_class.rb has to look like this

module WhateverModule
  class WhateverClass
  end
end

Or you define the module in a file besides the whatever_module folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM