工厂女孩未初始化的常量模型名称与rails-api [英] Factory Girl uninitialized constant Model Name with rails-api
问题描述
我正在尝试为User模型制造工厂,但是当我运行rspec时,我得到了
I'm trying to make a factory for my User model, but when I run rspec, I get
Failure/Error: user = build(:user, email: "invalid@email.com")
NameError:
uninitialized constant User
当我跳入Rails控制台时,我可以执行 User.all
,它将返回我拥有的用户和 FactoryGirl.build(:user,email:"invalid@email.com)
正常工作,所以我不确定问题出在哪里.
When I hop into rails console, I can do User.all
and it will return the users I have and FactoryGirl.build(:user, email: "invalid@email.com")
works just fine, so I'm not sure where the problem is.
我已经使用rails 4.2 ruby 2.2使用rails-api创建了项目
I've created the project with rails-api, using rails 4.2 ruby 2.2
# spec/spec_helper.rb
# i have to set spec/factories as the location explicitly or it won't find the factories
require 'factory_girl_rails'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)]
FactoryGirl.find_definitions
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
end
# spec/factories/user.rb
FactoryGirl.define do
factory :user do
email "test@example.com"
password "password"
end
end
#spec/requests/api/v1/sign_in_spec.rb
require 'spec_helper'
describe "Signing In" do
it "will reject an invalid user" do
user = build(:user, email: "invalid@email.com")
post :new_api_v1_user_session, user: { email: user.email, password: user.password}
is_expected.to respond_with 401
end
end
#Gemfile
ruby '2.2.0'
gem 'rails', '4.2.0'
gem 'rails-api'
gem 'spring', :group => :development
gem 'pg'
gem 'active_model_serializers', '0.8.3'
gem 'devise'
gem 'simple_token_authentication'
gem 'rdoc'
gem 'responders'
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
end
谢谢!
更新:我可以在 rails console test
上运行 FactoryGirl.build(:user)
,没有任何问题...
Update: I can run FactoryGirl.build(:user)
with rails console test
without any issues...
推荐答案
我所需要做的只是在spec_helper.rb中 require'rails_helper'
.这也使我可以从spec_helper中删除FactoryGirl.definition_file_paths.
Looks like all I needed to do was require 'rails_helper'
in my spec_helper.rb. This also allowed me to remove the FactoryGirl.definition_file_paths from spec_helper.
这篇关于工厂女孩未初始化的常量模型名称与rails-api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!