这是我在尝试使用RSpec运行测试时遇到的错误:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-3.2.11/lib/active_support/infl
ector/methods.rb:230:in `block in constantize': uninitialized constant User (Nam
eError)
我正在尝试使用RSpec运行FactoryGirl但没有Rails。以下是参与测试的文件:
user_spec.rb
require 'spec_helper'
module Bluereader
describe User do
describe 'login' do
user = FactoryGirl.build(:user)
end
describe 'logout' do
end
describe 'create_account' do
end
describe 'delete_account' do
end
end
end
规格/ spec_helper
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'lib/bluereader'
require 'factory_girl'
FactoryGirl.find_definitions
规格/ factories.rb
require 'digest/sha1'
FactoryGirl.define do
sequence(:username) { |n| "user-#{n}" }
factory :user do
username
encrypted_password Digest::SHA1.hexdigest('password')
full_name 'John Doe'
logged_in_at Time.now
logged_out_at 0
end
end
此时我知道正在加载factories.rb
文件(我尝试使用moronic打印调试)。当我从 user_spec.rb 中删除user = FactoryGirl.build(:user)
行时,我没有错误(正常的RSpec反馈告诉我没有测试,但没有错误)。如果你有兴趣,这是我的模特:
要求'digest / sha1'
module Bluereader
class User < ActiveRecord::Base
has_many :categories, :foreign_key => :user_id
has_many :news, :foreign_key => :user_id
has_many :settings, :foreign_key => :user_id
attr_reader :full_name
class << self
def login(username, password)
encrypted_password = Digest::SHA1.hexdigest(password)
if not User.exists?(:username => username, :encrypted_password => encrypted_password)
user_id = User.id_from_username(username)
update(user_id, :logged_in_at => Time.now, :logged_out_at => 0)
end
end
def logout
update(current_user.id, :logged_out_at => Time.now)
end
def validate_account(username, password, full_name)
if username.empty? or password.empty or full_name.empty?
return 'Please fill in all the fields.'
end
if User.exists?(:username => username)
return 'That username is already in use.'
end
unless username =~ /^\w+$/
return 'Username field should contain only letters, numbers and underscores.'
end
''
end
def create_account(username, password, full_name)
encrypted_password = Digest::SHA1.hexdigest(password)
User.create(:username => username,
:encrypted_password => encrypted_password,
:full_name => full_name,
:logged_in_at => Time.now,
:logged_out_at => 0)
end
def delete_account
current_user.destroy
end
private
def id_from_username(username)
user = where(:username => username).first
user.nil? ? 0 : user.id
end
def current_user
where(:logged_out_at => 0).first
end
end
end
end
解
问题是User类在一个模块中,这是解决方案:
factory :user, class: Bluereader::User do
答案 0 :(得分:1)
您需要在规范帮助文件中要求rails环境。将以下内容添加到spec / spec_helper.rb:
require File.expand_path("../../config/environment", __FILE__)
<强>更新强>
即使你没有使用Rails,你仍然需要在规范助手中要求模型。
答案 1 :(得分:1)
从问题底部开始
问题是User类位于模块中,这是解决方案:
let noDuplicates = [...new Set(operatorsInput)];
答案 2 :(得分:0)
对于像我这样笨手笨脚的人来说,您的代码中可能有 FactoryGirl
,而您本来打算有 FactoryBot