Rspec에 내 모델 클래스가 표시되지 않습니다. 초기화되지 않은 상수 오류
Ruby on Rails 애플리케이션에서 내 모델에 대한 Rspec 테스트를 작성하고 있습니다. 그리고 'rspec spec'을 시작하는 동안이 오류가 발생합니다.
command:
/spec/models/client_spec.rb:4:in `<top (required)>': uninitialized constant Client (NameError)
Rails 4.0.0과 Ruby 2.0.0을 사용합니다.
내 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
그리고 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
그리고 마지막으로 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
내 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
귀하의 spec_helper
파일은 몇 가지 중요한 명령이 없습니다. 특히 config / environment 및 초기화를 포함하지 않습니다 rspec-rails
.
spec/spec_helper.rb
파일 시작 부분에 다음 줄을 추가 할 수 있습니다.
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
또는 그냥 실행할 수 있습니다
rails generate rspec:install
와 spec_helper
함께 사용하기 위해 생성 된 것으로 덮어 씁니다 rspec-rails
.
레일 4.x (rspec-rails 3.1.0) 사용
require "rails_helper" # this
아니
require "spec_helper" # not 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.
I'm using Rails 5.0.0.1.
Here's how I resolved this concern.
On your Gemfile, please add -> 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"
Now, execute this command on the terminal.
bundle install
Once bundle command went good, execute the rails generate. Like so,
rails generate rspec:install
Reason: this command will create a new .rspec(hit overwrite when prompted), spec/rails_helper.rb and 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
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.
Hope this helps!
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.
I have solved my problems reading the rspec-rails gem documentation :
https://github.com/rspec/rspec-rails#model-specs
where it confirms what Swards says about requiring "rails_helper" not "spec_helper" anymore.
Also my model specification looks more like the one from the gem docs
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
Factories folder define in your app
FactoryBot.define do
factory :user_params , :class => 'User' do
username 'Alagesan'
password '$1234@..'
end
end
Your Controller RSpec file:
it 'valid params' do
post :register, params: {:user => user_params }
end
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.rb
file, see if there isconfig.eager_load = false
, set it totrue
.
You should check in the written order since you don't want to solve the issue with the typo laying there.
'Nice programing' 카테고리의 다른 글
Pycharm이 플롯을 표시하지 않습니다. (0) | 2020.10.08 |
---|---|
두 ArrayList의 차이를 어떻게 계산할 수 있습니까? (0) | 2020.10.08 |
Mac OS Sierra에서 Brew로 노드 설치 실패 (0) | 2020.10.08 |
android-갤러리에 이미지 저장 (0) | 2020.10.08 |
콘솔 애플리케이션에 이미지 표시 (0) | 2020.10.08 |