Ruby-on-rails Rspec 没有看到我的模型类。未初始化的常量错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17507416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rspec doesn't see my model Class. uninitialized constant error
提问by Stan
I'm writing tests on Rspec for my models in Ruby on Rails application. And I receive this error while starting 'rspec spec'
我正在为我在 Ruby on Rails 应用程序中的模型编写 Rspec 测试。我在启动“rspec spec”时收到此错误
command:
/spec/models/client_spec.rb:4:in `<top (required)>': uninitialized constant Client (NameError)
I use Rails 4.0.0 and Ruby 2.0.0
我使用 Rails 4.0.0 和 Ruby 2.0.0
Here is my client_spec.rb:
这是我的 client_spec.rb:
require 'spec_helper'
describe Client do
it 'is invalid without first_name', :focus => true do
client = Client.new
client.should_not be_valid
end
end
And Gemfile:
和 Gemfile:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.rc1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc1'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more:
gem 'turbolinks'
gem 'jbuilder', '~> 1.0.1'
group :development do
gem 'rspec-rails'
end
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
group :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'database_cleaner'
end
And at last client.rb (ROR Model and Class):
最后是 client.rb(ROR 模型和类):
class Client < ActiveRecord::Base
has_many :cars
has_many :orders
has_one :client_status
has_one :discount_plan, through: :client_status
validates :email, format: { with: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})\z/, :message => "Only emails allowed", :multiline => true }
validates :email, presence: true, if: "phone.nil?"
#validates :phone, presence: true, if: "email.nil?"
validates :last_name, :first_name, presence: true
validates :last_name, :first_name, length: {
minimum: 2,
maximum: 500,
wrong_length: "Invalid length",
too_long: "%{count} characters is the maximum allowed",
too_short: "must have at least %{count} characters"
}
end
If it'd be useful my spec_helper.rb file:
如果它对我的 spec_helper.rb 文件有用:
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
#config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
回答by Mark Swardstrom
In rails 4.x (rspec-rails 3.1.0) use
在 rails 4.x (rspec-rails 3.1.0) 中使用
require "rails_helper" # this
not
不是
require "spec_helper" # not this
in your spec files
在您的规范文件中
回答by gmacdougall
Your spec_helperfile is missing some important commands. Specifically, it's not including config/environment and initializing rspec-rails.
您的spec_helper文件缺少一些重要的命令。具体来说,它不包括 config/environment 和 initializing rspec-rails。
You can add the following lines to the start of your spec/spec_helper.rbfile
您可以将以下行添加到spec/spec_helper.rb文件的开头
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
or you can just run
或者你可以运行
rails generate rspec:install
and overwrite your spec_helperwith one generated for use with rspec-rails.
并spec_helper用生成的与rspec-rails.
回答by Umang Raghuvanshi
You might also like to add --require rails_helperin your .rspecfile so that it looks like this.
您可能还想添加--require rails_helper到您的.rspec文件中,使其看起来像这样。
--color
--require spec_helper
--require rails_helper
You won't need to require rails_helper in all your specs, after this.
在此之后,您将不需要在所有规范中都需要 rails_helper。
回答by Kent Aguilar
I'm using Rails 5.0.0.1.
Here's how I resolved this concern.
我正在使用Rails 5.0.0.1。
这是我解决这个问题的方法。
On your Gemfile, please add -> gem 'rspec-rails', ">= 2.0.0.beta"
在您的 Gemfile 上,请添加 -> gem 'rspec-rails', ">= 2.0.0.beta"
Like so,
像这样,
group :development, :test do
gem 'rspec-rails', ">= 2.0.0.beta"
end
Reason:if the rspec-rails is not added and when you execute the rspec command, it will generate this error -> "cannot load such file -- rails_helper"
原因:如果没有添加rspec-rails,在执行rspec命令时,会产生这个错误-> “无法加载此类文件--rails_helper”
Now, execute this command on the terminal.
现在,在终端上执行此命令。
bundle install
捆绑安装
Once bundle command went good, execute the rails generate. Like so,
一旦 bundle 命令运行良好,执行 rails generate。像这样,
rails generate rspec:install
rails 生成 rspec:install
Reason:this command will create a new .rspec(hit overwrite when prompted), spec/rails_helper.rb and spec/spec_helper.rb
原因:此命令将创建一个新的 .rspec(提示时点击覆盖)、spec/rails_helper.rb 和 spec/spec_helper.rb
Now, at this point, rspec should pretty much run properly.
However, if you encounter an error where in the model is not found e.g. cannot load such file -- idea, try adding this on top of your spec/spec_helper.rb
现在,在这一点上,rspec 应该几乎可以正常运行。
但是,如果您遇到在模型中找不到的错误,例如无法加载此类文件——idea,请尝试将其添加到您的 spec/spec_helper.rb 之上
require 'rubygems'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
Reason:seems that spec_helper is not loading the Rails environment. We're requiring it.
原因:似乎 spec_helper 没有加载 Rails 环境。我们要求它。
Hope this helps!
希望这可以帮助!
回答by Arnaud Bouchot
Things have moved a bit since this thread has been created, I have experienced the uninitialized constant ClassName (NameError)error too using Ruby 2.1, Rails 4.2, rspec-rails 3.3.
自从创建这个线程以来,事情发生了一些变化,我在uninitialized constant ClassName (NameError)使用 Ruby 2.1、Rails 4.2、rspec-rails 3.3 时也遇到了这个错误。
I have solved my problems reading the rspec-rails gem documentation :
我已经解决了阅读 rspec-rails gem 文档的问题:
https://github.com/rspec/rspec-rails#model-specs
https://github.com/rspec/rspec-rails#model-specs
where it confirms what Swards says about requiring "rails_helper" not "spec_helper" anymore.
它证实了 Swards 关于要求“rails_helper”而不是“spec_helper”的说法。
Also my model specification looks more like the one from the gem docs
此外,我的模型规范看起来更像是 gem 文档中的规范
RSpec.describe Url, :type => :model do
it 'is invalid without first_name', :focus => true do
client = Client.new
client.should_not be_valid
end
end
回答by Boobalan
Factories folder define in your app
工厂文件夹在您的应用程序中定义
FactoryBot.define do
factory :user_params , :class => 'User' do
username 'Alagesan'
password '34@..'
end
end
Your Controller RSpec file:
您的控制器 RSpec 文件:
it 'valid params' do
post :register, params: {:user => user_params }
end
回答by Longfei Wu
If other answers under this question don't work, try:
如果此问题下的其他答案不起作用,请尝试:
- Check if there is any typo in the file name or class name (they should match)
- 检查文件名或类名中是否有拼写错误(它们应该匹配)
Other wise,
除此以外,
- Check your
config/environment/test.rbfile, see if there isconfig.eager_load = false, set it totrue.
- 检查您的
config/environment/test.rb文件,看看是否有config.eager_load = false,将其设置为true.
You should check in the written order since you don't want to solve the issue with the typo laying there.
您应该检查书面订单,因为您不想解决存在拼写错误的问题。

