首页 > 解决方案 > 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?

标签: ruby-on-railsrubyrspecruby-on-rails-5rspec-rails

解决方案


您的规范文件应该在

spec/services/distamce/whatever_class_spec.rb.

在您的情况下, rspec 尝试查找 WhatModule 因为/whatever_module/在您的规范文件路径中。您可以尝试将此更改为spec/services/foo_bar/whatever_class_spec.rb,您将收到缺少的 FooBarModule 错误。

我想我知道你错过了什么。

Rspec 不会自动要求您的 app 文件夹,因此最初 app 文件夹中没有可用的模块或类。

当您检查https://github.com/rspec/rspec-rails#installation @2 时,您可以看到您必须为 rspec 添加一些样板文件,例如rails_helper.rbspec_helper.rbwith rails generate rspec:install。这些负责所有与 rspec 相关的设置和 app 文件夹的要求。

还需要require 'rails_helper'在每个规范文件之上添加。

完成所有这些并收到错误Unable to autoload constant WhateverModule::WhateverClass后,您whatever_class.rb必须看起来像这样

module WhateverModule
  class WhateverClass
  end
end

或者您在文件夹之外的文件中定义模块whatever_module


推荐阅读