Rspec doesn't see my model Class. uninitialized constant error

后端 未结 7 1893
予麋鹿
予麋鹿 2021-01-30 19:09

I\'m writing tests on Rspec for my models in Ruby on Rails application. And I receive this error while starting \'rspec spec\'

command:
/spec/models/client_spec         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 19:58

    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!

提交回复
热议问题