问题
When I try to run my spec, I get an uninitialized constant error. My spec looks like this:
describe Facility do
it { should have_many(:units) }
it { should have_many(:facilities_users) }
it { should have_many(:administrators) }
it { should have_many(:facility_employees) }
end
The error is:
facility_spec.rb:1:in `<top (required)>': uninitialized constant Facility (NameError)
I certainly have a Facility model, so I'm not sure why this would happen.
回答1:
You should try running rake spec
instead of rspec spec
.
But both may work.
If not working try Try bundle exec rspec spec
or bundle exec rake spec
.
Source: When trying to run rspec I get uninitialized constant.
回答2:
Add the following at the top of your file:
require 'spec_helper'
回答3:
If you are using the 'rspec-rails' gem, then run
rails g rspec:install
This will create the spec/spec_helper.rb
file (you should edit it if you're not using ActiveRecord so it runs you spec setup correctly).
After that, ensure you are requiring the helper at the top of your spec files:
require 'spec_helper'
If this didn't work for you, there might be more issues like:
- You're trying to test a file under the lib/ directory. In this case, make sure this file is loaded with the environment (config/application.rb -> autoload_paths) or require it explicitly.
- The constant actually doesn't exist. It could be inside a namespace or just a typo.
回答4:
In the spec file, require the file where Facility
class is defined.
来源:https://stackoverflow.com/questions/12958985/why-wont-my-rails-spec-run