gpt4 book ai didi

ruby-on-rails - 将 MiniTest 迁移到 RSpec 时出错

转载 作者:行者123 更新时间:2023-12-03 17:27:28 30 4
gpt4 key购买 nike

我正在尝试将我的 rails 应用程序迁移到 RSpec。但我收到错误 uninitialized constant ActiveRecord::Relation运行规范时。它说它在 application.rb 的第 10 行,即 Bundler.require(:default, Rails.env) if defined?(Bundler)
错误信息

An error occurred while loading rails_helper.
Failure/Error: require File.expand_path('../config/environment', __dir__)

NameError:
uninitialized constant ActiveRecord::Base
# ./config/application.rb:12:in `<top (required)>'
# ./config/environment.rb:4:in `require'
# ./config/environment.rb:4:in `<top (required)>'
# ./spec/rails_helper.rb:11:in `require'
# ./spec/rails_helper.rb:11:in `<top (required)>'
# ------------------
# --- Caused by: ---
# NameError:
# uninitialized constant ActiveRecord::Base
# ./config/application.rb:12:in `<top (required)>'

规范
require 'rails_helper'

RSpec.describe Api::V1::CertificateRequestsController, type: :controller do
describe '#create_v1_4' do
it 'worked' do
expect(true).to eq(true)
end
end
end

spec_helper.rb
# frozen_string_literal: true

RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end

# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end

# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
end

rails_helper.rb
# frozen_string_literal: true

# This file is copied to spec/ when you run 'rails generate rspec:install'
puts "Your env: #{ENV.fetch('RAILS_ENV', 'test')}"

require 'spec_helper'
require 'database_cleaner'
require 'pry'

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# binding.pry

# Prevent database truncation if the environment is production
if Rails.env.production?
abort('The Rails environment is running in production mode!')
end
require 'rspec/rails'
# include Warden::Test::Helpers
# Warden.test_mode!
# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories.
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true

# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
config.infer_spec_type_from_file_location!

# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")

config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end

config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end

application.rb
# frozen_string_literal: true

require File.expand_path('boot', __dir__)
require 'oauth/rack/oauth_filter'
require 'rack/ssl-enforcer'
require 'rails/all'
require './lib/middleware/catch_json_parse_errors'

Bundler.setup
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

CLIENT_OPTIONS = ['aswesome.com', 'aswementer'].freeze
DEPLOYMENT_CLIENT = CLIENT_OPTIONS[0]

Struct.new('Expiring', :before, :after, :cert)
Struct.new('Notification', :before, :after, :domain, :expire, :reminder_type, :scanned_certificate_id)
Struct.new('Reminding', :year, :cert)

module AwesomeApp
class Application < Rails::Application
# set environment variables
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'local_env.yml')
YAML.safe_load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value
end
end

# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.

# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W[#{config.root}/lib]

Bundler.require(*Rails.groups)
# Config::Integration::Rails::Railtie.preload

# Add additional load paths for your own custom dirs
%w[observers mailers middleware serializers].each do |dir|
config.autoload_paths << "#{config.root}/app/#{dir}"
end

# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]

# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Central Time (US & Canada)'

# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de

# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'

# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += %i[password password_confirmation]
# config.action_mailer.default_url_options = { :host => Settings.actionmailer_host }

# machinist generator
# config.generators do |g|
# g.fixture_replacement :machinist
# end

# Rails Api
config.api_only = false

# turn off strong parameters
config.action_controller.permit_all_parameters = true

config.generators do |g|
g.test_framework :minitest, spec: true, fixture: false
g.jbuilder false
end

# config.middleware.use OAuth::Rack::OAuthFilter
config.middleware.insert_before ActionDispatch::ParamsParser, 'CatchJsonParseErrors'

# Delayed Job
config.active_job.queue_adapter = :delayed_job

config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/certificate/*',
headers: :any,
methods: %i[get post delete put options head],
max_age: 0
end
end

# Enable the asset pipeline
config.assets.enabled = true

config.sass.preferred_syntax = :sass
config.sass.line_comments = false
config.sass.cache = false
config.action_mailer.default_url_options = { host: 'secure.ssl.com', protocol: 'https' }
if DEPLOYMENT_CLIENT =~ /certassure/i && Rails.root.to_s =~ /Development/
paths['config/database'] = 'config/client/certassure/database.yml'
end
end
end

require "#{Rails.root}/lib/base.rb"
require "#{Rails.root}/lib/asset_tag_helper.rb"
require "#{Rails.root}/lib/array.rb"
require "#{Rails.root}/lib/range.rb"
require "#{Rails.root}/lib/in_words.rb"
require "#{Rails.root}/lib/kernel.rb"
require "#{Rails.root}/lib/money.rb"
# require "#{Rails.root}/lib/subdomain-fu.rb"
require "#{Rails.root}/lib/domain_constraint.rb"
require "#{Rails.root}/lib/preferences.rb"
require "#{Rails.root}/lib/active_record.rb"
require "#{Rails.root}/lib/active_record_base.rb"
require "#{Rails.root}/lib/hash.rb"
require 'will_paginate'

# try to figure this out for heroku and rails 3
# class Fixnum; include InWords; end
# class Bignum; include InWords; end
DB_STRING_MAX_LENGTH = 255
DB_TEXT_MAX_LENGTH = 40_000
HTML_TEXT_FIELD_SIZE = 20
AMOUNT_FIELD_SIZE = 10
ADDRESS_FIELD_SIZE = 30
SERVER_SIDE_CART = false
# SQL_LIKE = Rails.configuration.database_configuration[Rails.env]['adapter'].
# downcase=='postgresql' ? 'ilike' : 'like'
db_env = Rails.configuration.database_configuration[Rails.env]
db_adapter = db_env['adapter'].downcase if db_env.present?
SQL_LIKE = db_adapter == 'postgresql' ? 'ilike' : 'like'

# uncomment to track down bugs on heroku production
# ApplicationRecord.logger.level = 0 # at any time
ActiveMerchant::Billing::CreditCard.require_verification_value = false
PublicSuffix::List.default =
PublicSuffix::List.parse(File.read(PublicSuffix::List::DEFAULT_LIST_PATH), private_domains: false)

Gemfile
# frozen_string_literal: true

source 'http://rubygems.org'

gem 'activemerchant'
gem 'acts_as_publishable'
gem 'authlogic'
gem 'awesome_print'
gem 'aws-sdk', '~> 2.0'
gem 'bootsnap', require: false
gem 'declarative_authorization', git: 'https://github.com/xymist/declarative_authorization.git', branch: 'allow_rails_5'
gem 'dynamic_form'
gem 'easy_roles'
gem 'haml', '>= 3.1.alpha.50'
gem 'json' # , '~> 1.8.6'
gem 'money', '2.1.0'
gem 'mysql2'
gem 'paperclip', '~> 5.3.0'
gem 'protected_attributes'
gem 'pry-rails'
gem 'rabl', '0.14.1'
gem 'rack-ssl-enforcer'
gem 'rails', '~> 4.2.11.1'
gem 'rb-inotify', require: false
gem 'responders', '~> 2.0'
gem 'savon', '~> 2.0'
gem 'sprockets'
gem 'squeel'
gem 'will_paginate'
gem 'workflow', '~> 1.2'
gem 'xml-simple'
gem 'yui-compressor'
gem 'zip-zip'
# Commented out while converting to pipeline
# gem 'jammit'
gem 'config'
gem 'oauth-plugin', '>= 0.4.0.pre1'
gem 'openssl-extensions', require: 'openssl-extensions/all'
gem 'radix62'
gem 'simpleidn'
gem 'uuidtools'
gem 'whenever', require: false
# gem "therubyracer", '~> 0.12.3', platform: :ruby
gem 'actionpack-action_caching', '~> 1.1', '>= 1.1.1'
gem 'airbrake', '~> 9.5' # https://airbrake.io/docs/ruby/upgrading-your-notifier/
gem 'api-pagination'
gem 'attr_encrypted', '>= 3.0.3'
gem 'bootstrap'
gem 'cancan'
gem 'coffee-rails'
gem 'compass-rails'
gem 'daemons'
gem 'dalli'
gem 'dalli-elasticache'
gem 'delayed-web'
gem 'delayed_job_active_record'
gem 'delayed_job_groups_plugin'
gem 'jbuilder'
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'json-schema'
gem 'jsonapi-serializers'
gem 'libv8'
gem 'mini_racer', platforms: :ruby
gem 'nokogiri', '>= 1.10.4'
gem 'popper_js', '~> 1.11.1'
gem 'public_suffix', '>= 4.0.0'
gem 'rack-cors', '>= 0.4.1', require: 'rack/cors'
gem 'rails-api'
gem 'rails-observers'
gem 'request_exception_handler'
gem 'rubyzip', '>= 1.3.0'
gem 'rvm-capistrano'
gem 'sass-rails'
gem 'sdoc', group: :doc
gem 'select2-rails'
gem 'stripe'
gem 'turbolinks'
gem 'unscoped_associations'
# gem 'wkhtmltopdf-binary' see config/initializers/wicked_pdf.rb for installation instructions
gem 'duo_web', '~> 1.0'
gem 'u2f'
gem 'wicked_pdf'
# gem 'simple_captcha2', require: 'simple_captcha'
gem 'acts_as_tree'
gem 'font-awesome-rails'
gem 'recaptcha', require: 'recaptcha/rails'
gem 'where-or'
gem 'whois', '~> 4.0'
gem 'whois-parser'
# gem "skylight"
gem 'authy'
gem 'mailboxer'
gem 'memoist'
# gem 'countries'
gem 'bootstrap-datepicker-rails'
gem 'timezone', '~> 1.0'
# required by sws-a1
gem 'activerecord-import'
gem 'date'
gem 'etc'
gem 'fileutils', '~> 1.1.0'
gem 'forwardable'
gem 'scout_apm'
gem 'stringio'
gem 'strscan'
gem 'zlib'

group :development do
gem 'annotate'
gem 'better_errors'
gem 'binding_of_caller'
gem 'bullet'
gem 'dotenv-rails'
gem 'letter_opener_web', '~> 1.0'
gem 'memory_profiler'
gem 'meta_request'
gem 'spring'
gem 'spring-commands-testunit'
gem 'web-console', '~> 2.0'

# Linting
gem 'rubocop', require: false
gem 'rubocop-performance'
gem 'rubocop-rails'
gem 'solargraph', require: false
end

group :development, :test do
gem 'builder'
gem 'byebug'
gem 'factory_bot_rails'
gem 'pry-byebug'
gem 'pry-remote'
gem 'ruby-odbc'
gem 'ruby_parser'
gem 'rspec-rails'
end

group :test do
gem 'database_cleaner'
gem 'faker'
gem 'mocha'
gem 'simplecov', require: false
gem 'vcr'
gem 'webmock'
end

gem 'foreman'
gem 'httparty'
gem 'swagger-blocks'
gem 'swagger-docs'
gem 'uglifier', '4.1.8'

gem 'rswag-ui'

gem 'bcrypt_pbkdf', '~> 1'
gem 'ed25519', '~> 1.2'

test.rb
SslCom::Application.configure do
MIGRATING_FROM_LEGACY = false
# Settings specified here will take precedence over those in config/environment.rb

# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true

# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false

# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false

# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false

# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = {host: 'localhost:3000'}

config.after_initialize do
Rails.application.routes.default_url_options = {host: 'localhost:3000'}
end

config.force_ssl = false

# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql

# Sort the order test cases are executed.
config.active_support.test_order = :sorted

# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr

ActiveMerchant::Billing::Base.mode = :test

config.eager_load=false

config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"

#config.log_level = Logger::INFO

GATEWAY_TEST_CODE=1.0
# END ActiveMerchant configuration
end

#require "#{Rails.root}/lib/firewatir_url.rb"

最佳答案

我的猜测是 RAILS_ENV环境变量设置为除 test 以外的其他值当您运行 rspec 时命令。我以前在一些具有 RAILS_ENV 的机器上遇到过这种情况。环境变量显式设置为 development或其他完全不同的东西(就像其他人提到的那样会导致您看到的问题,因为该值缺少环境文件)。

在您的 rails_helper.rb文件,尝试更改这一行:

ENV['RAILS_ENV'] ||= 'test'

对此:
ENV['RAILS_ENV'] = 'test'

看看你的测试是否可以运行。如果是这种情况,您将需要找到您拥有 RAILS_ENV 的位置。手动设置(通常在 shell 配置文件中)并删除它,或复制您的 config/environments/test.rb文件到新文件以匹配任何内容 RAILS_ENV被设定为。

关于ruby-on-rails - 将 MiniTest 迁移到 RSpec 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182426/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com