我试图让一个工厂为我的用户模型,但是当我运行rspec的,我得到
Failure/Error: user = build(:user, email: "invalid@email.com")
NameError:
uninitialized constant User
当我跳进铁轨控制台,我可以做User.all
,它将返回我有用户和FactoryGirl.build(:user, email: "invalid@email.com")
工作得很好,所以我不知道在哪里问题是。
我已经创建了Rails的API项目,使用Rails 4.2红宝石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
谢谢!
更新:我可以运行FactoryGirl.build(:user)
与rails console test
没有任何问题......