I am using Rails 4.2 with Ruby 2.2 and rspec for testcases. I have set
Rails.env = 'test'
in both my spec_helper and rails_helper. Here is my database.yml file:
development:
adapter: postgresql
encoding: unicode
database: app_dev
pool: 5
username: postgres
password: root
test:
adapter: postgresql
encoding: unicode
database: app_test
pool: 5
username: postgres
password: root
production:
adapter: postgresql
encoding: unicode
database: app_prod
pool: 5
username: postgres
password: root
Here is my rails_helper:
Rails.env = 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include JsonHelper
config.include PathHelper
config.include S3Helper
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'yaml'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AppName
class Application < Rails::Application
config.generators do |g|
g.assets = false
g.helper = false
g.views = false
end
# Load all locale files
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.load_path += Dir[Rails.root.join(
'config', 'locales', '**', '**', '*.{rb,yml}')]
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/workers/"]
config.action_controller.include_all_helpers = false
config.active_record.schema_format = :sql
config.i18n.available_locales = [:en, :hi, :mr]
config.i18n.default_locale = :hi
config.i18n.fallbacks = [:en]
config.active_record.raise_in_transactional_callbacks = true
end
end
Gemfile:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# Turbolinks makes following links in your web application faster
gem 'turbolinks', '~> 2.5.3'
# Use Unicorn as the app server
gem 'unicorn', '~> 4.9.0'
# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.0.4'
# Integrate the jQuery Validation plugin into the Rails asset pipeline
gem 'jquery-validation-rails', '~> 1.13.1'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# use swagger for api documentation
gem 'swagger-docs', '~> 0.1.9'
# for consuming restful web services
gem 'httparty', '~> 0.13.5'
# for ActiveRecord model/data translations
gem 'globalize', '~> 5.0.0'
# generates accessors for translated fields
gem 'globalize-accessors', '~>0.2.1'
# Amazon Web service SDK Ruby
gem 'aws-sdk', '~> 2.1.0'
# cloud services for S3
gem 'fog', '~> 1.33.0'
# handle file uploads
gem 'carrierwave', '~>0.10.0'
# Photo Resizing
gem 'mini_magick', '~> 4.2.7'
# Background Jobs
gem 'sidekiq', '~> 3.4.2'
# Geocoder
gem 'geocoder', '~> 1.2.9'
# active admin
gem 'activeadmin', '~> 1.0.0.pre1'
# for authentication
gem 'devise', '~> 3.5.1'
# for roles of active admin
gem 'rolify', '~> 4.0.0'
# for authorization
gem 'cancan', '~> 1.6.10'
group :development, :test do
# Debugging using pry
gem 'pry-rails', '~> 0.3.4'
gem 'pry-byebug', '~> 3.1.0'
# testing framework for rails
gem 'rspec-rails', '~> 3.1.0'
gem 'rspec-collection_matchers', '~> 1.1.2'
gem 'factory_girl_rails', '~> 4.4.1'
gem 'shoulda-matchers', '~> 2.8.0'
# code test coverage
gem 'simplecov', '~> 0.7.1'
gem 'simplecov-rcov', '~> 0.2.3'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# speeds up development by keeping your application running in the background
gem 'spring', '~> 1.3.6'
end
group :development do
# generates ER diagrams for rails application
gem 'rails-erd', '~> 1.4.1'
end
group :test do
# set of strategies for cleaning your database
gem 'database_cleaner', '~> 1.3.0'
end
When I run my test cases, Rails.env is 'test' as expected (used pry to verify). However my test cases are always hitting the development database.
Rails.env
#=> "test"
ActiveRecord::Base.connection_config
#=> {:adapter=>"postgresql", :encoding=>"unicode", :database=>"app_dev", :pool=>5, :username=>"postgres", :password=>"root"}
spec_helper:
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'simplecov'
require 'simplecov-rcov'
require 'database_cleaner'
require 'factory_girl_rails'
ENV['RAILS_ENV'] ||= 'test'
SimpleCov.start
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# Database Cleaner
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
Rails.application.load_seed
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
I have been scratching my head since last few hours but nothing seems to solve the mystery. Any help would be greatful!
The reason your tests hit the development database is because you have defined ENV['DATABASE_URL'] somewhere in your environment.
There are two ways of specifying the database connection to be used:
Specifying the ENV['DATABASE_URL']
Using the very popular database.yml file
In many cases the first one takes prescedence over the latter.
I realized I had a problem similar to yous after using ENV['DATABASE_URL'] to set my production database, only to find out that all my environments (test & development) suddenly had started to use my production database regardless of content in database.yml.
To solve my problem all I did was change the name on the environment variable to something else, so that it no longer overwrite my database.yml configurations.
Reading this will solve your problem: Connection Preference information
It sounds as though somewhere in your environment (maybe one of your gems) it is setting your environment to dev or establishing a connection to your dev database.
To explicitly make it connect to the test database, add:
ActiveRecord::Base.establish_connection
to your rails_helper.
Prime candidate for troublemaker would be `gem 'rails-erd', '~> 1.4.1'. If you have this as auto-generating the diagram on migrate, when the test schema is migrated, it will connect to the dev database to dump a diagram.
Try removing this gem or perhaps the '.rake' file and see what happens.
Your rails_helper looks strange. The first line says:
Rails.env = 'test'
At the first line you don't have Rails loaded yet (I suppose you run RSpec using bundle exec rspec). So it should raise an error.
Therefore I made a small change in rails_helper:
require File.expand_path('../../config/environment', __FILE__)
Rails.env = 'test'
require 'spec_helper'
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# the rest
Now putting
expect(ActiveRecord::Base.connection_config[:database]).to match(/test/)
somewhere in your spec, should pass successfully.
1) Add require: false to the declaration of 'rails-erd' gem
gem 'rails-erd', '~> 1.4.1', require: false
2) In your spec_helper.rb, replace Rails.env = 'test' by ENV['RAILS_ENV'] ||= 'test'
3) Verify in your bin/rspec (if present) that you don't have any instruction changing the value of env
4) Then stop spring from the command line
spring stop
5) Run your specs from the command line
rspec
You can run rspc with RAILS_ENV=test bundle exec rspec spec
Also you can put inside rails_helper.rb
Rails.env = 'test'
Also move testing framework section from development test to test inside gemfile
group :test do
# testing framework for rails
gem 'rspec-rails', '~> 3.1.0'
gem 'rspec-collection_matchers', '~> 1.1.2'
gem 'factory_girl_rails', '~> 4.4.1'
gem 'shoulda-matchers', '~> 2.8.0'
# set of strategies for cleaning your database
gem 'database_cleaner', '~> 1.3.0'
end
My answer applies to anyone who is using Rspec with Ruby outside of Rails. For example, let's say you are creating a Ruby gem. Well, you can still add a database.yml in a config folder in your project and specify a test option:
test:
adapter: 'mysql2'
encoding: utf8mb4
collation: utf8mb4_bin
pool: 1
username: root
password:
host: localhost
database: 'my_site_test'
Now you can add the following in spec_helper.rb:
config.before :suite do
ActiveRecord::Base.establish_connection(YAML.load(File.open(File.expand_path("../../lib/my_gem_config/database.yml", __FILE__)))["test"])
end
The :suite scope indicates that the block of code should be run once before the suite of tests, that means all of your tests.
Just put ENV["RAILS_ENV"] = "test" at the top of rails_helper
Related
I'm trying to migrate my rails application to RSpec. But I'm getting the error uninitialized constant ActiveRecord::Relation when running the specs. It says it's on line 10 of application.rb which is Bundler.require(:default, Rails.env) if defined?(Bundler)
error message
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)>'
Spec
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"
My guess is that the RAILS_ENV environment variable is set to something other than test when you run your rspec command. I've run into this before on some machines that have the RAILS_ENV environment variable explicitly set to development or something else entirely (which like others have mentioned will cause the issue you're seeing since the environment file is missing for that value).
In your rails_helper.rb file, try changing this line:
ENV['RAILS_ENV'] ||= 'test'
to this:
ENV['RAILS_ENV'] = 'test'
and see if your tests can run. If that is the case, you'll want to either find where you have RAILS_ENV manually set (typically in a shell configuration file) and remove it, or copy your config/environments/test.rb file to new one to match whatever it is RAILS_ENV is set to.
I had this problem when using Windows.
In order to run my Ruby on Rails app with Postgress and use PG gem, I had to set RUBY_DLL_PATH=<your-path-to-postgresql>/bin. Meaning that the RAILS_ENV environment variable is set to something other than test when you running rspec command.
The solution of #codenamev worked for me.
The problem was related to the order of the gems in the Gemfile. I had to comment out all of the gems and add them all back one by one while changing the order to fix any errors.
I am getting the following error when running RSpec
cannot load such file -- cucumber-rails
I am on Rails 4.2.7.1, rspec 3.5.4 and my cucumber tests successfully run when I do cucumber in app dir.
here's my rails_helper:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# 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. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
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")
end
Gemfile
source 'https://rubygems.org'
# used for searching
gem 'rbing'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.7.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :test do
gem 'rspec-rails'
gem 'cucumber-rails', :require => true
gem 'database_cleaner'
gem 'vcr'
gem 'webmock'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
gem 'guard-spork'
gem 'guard-cucumber'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
change
gem 'cucumber-rails', :require => true
to
gem 'cucumber-rails', :require => false
I don't want to run any Factories before I seed the database for some tests.
When I add require: false to factory_girl_rails I get the following error:
rails_helper.rb:37:in `block in <top (required)>': uninitialized constant FactoryGirl::Syntax (NameError)
Gem file:
source 'https://rubygems.org'
gem 'rails', '4.2.6'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'puma'
gem 'bootstrap-sass'
gem 'simple_form'
gem 'redcarpet' #This gem parses markup language to HTML
gem 'devise'
gem 'email_validator'
gem 'date_validator'
gem 'rolify'
gem 'country_select'
group :development do
gem 'web-console'
gem 'better_errors'
end
group :development, :test do
gem 'sqlite3'
gem 'byebug'
gem 'spring'
end
group :test do
gem 'spring-commands-rspec'
gem 'rspec-rails'
gem 'factory_girl_rails', require: false
gem 'faker'
gem 'capybara'
gem 'launchy'
gem 'selenium-webdriver'
gem 'database_cleaner'
gem 'shoulda-matchers', require: false
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
ruby "2.2.3"
rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'shoulda_helper'
require 'shoulda/matchers'
require 'devise'
require 'support/controller_macros'
# 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. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
#this allow me to not have to write FactoryGirl inside my tests
config.include FactoryGirl::Syntax::Methods
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
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.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
end
You have to require FactoryGirl so you can use it.
So one way would be deleting the require: false and the other way would be to require it in the rails_helper.rb using
require 'factory_girl_rails'
Please forgive any shortcomings in this (my first-ever) post on StackOverflow. I'm brand new to Ruby on Rails. I'm following the Rails Tutorial. I have spent many unsuccessful hours consulting other threads discussing the same Name Error that I'm raising in this question.
Any attempt of mine to run an rspec test like so: $bundle exec rspec spec/models/user_spec.rb
throws the now infamous error: `': uninitialized constant Rails (NameError)
Let me know if there's any more information I should provide you in order to get the ball rolling.
Here's my gemfile:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.1.2'
gem 'will_paginate', '3.0.4'
gem 'bootstrap-will_paginate', '0.0.9'
group :development, :test do
gem 'sqlite3', '1.3.8'
gem 'rspec-rails', '2.13.1'
# The following optional lines are part of the advanced setup.
# gem 'guard-rspec', '2.5.0'
# gem 'spork-rails', '4.0.0'
# gem 'guard-spork', '1.5.0'
# gem 'childprocess', '0.3.6'
end
group :test do
gem 'selenium-webdriver', '2.35.1'
gem 'capybara', '2.1.0'
gem 'factory_girl_rails', '4.2.0'
gem 'cucumber-rails', '1.4.0', :require => false
gem 'database_cleaner', github: 'bmabey/database_cleaner'
# Uncomment these lines on Linux.
# gem 'libnotify', '0.8.0'
# Uncomment these lines on Windows.
# gem 'rb-notifu', '0.0.4'
# gem 'win32console', '1.3.2'
# gem 'wdm', '0.1.0'
end
gem 'sass-rails', '4.0.1'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.1'
gem 'jquery-rails', '3.0.4'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
Here is my spec/models/user_spec.rb file:
require 'spec_helper'
describe User do
pending "add some examples to (or delete) #{__FILE__}"
end
Here is my app/models/user.rb file:
class User < ActiveRecord::Base
end
Here is my spec_helper.rb file:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
require 'test/unit'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# 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 before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.include Capybara::DSL
end
I have definitely run bundle install. I can also confirm that I've already created the database and run the migration (db/test.sqlite3 already exists)
In your spec_helper.rb, you have the following line twice:
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
Delete the first instance (the one on line 2). This is what is causing the error.
Having this line before require 'rspec/rails' will cause problems because we don't know what Rails is, and so we cannot call the root method.
The second instance (on line 13) is fine because this is after require 'rspec/rails'.
Remove redundant require 'spec_helper' line from your spec_helper.rb file.
Trying to resurrect an old project by upgrading gems. Ran into an issue where RSpec hangs on startup with the '--drb' option.
By itself, 'rspec spec' works fine. But start 'spork' in another terminal and then 'rspec --drb spec' spins up CPU to ~40% and just sits.
Using Rails 3.2.13, Ruby 1.9.3-p392, RSpec 2.13.1 and spork-rails 3.2.1, which depends on Spork 1.0.0rc3.
Gemfile
source 'http://rubygems.org'
gem 'rails', '~> 3.2.13'
gem 'devise', '~> 2.2.0'
gem 'event-calendar', :require => 'event_calendar'
gem 'has_scope'
gem 'high_voltage'
gem 'inherited_resources'
gem 'jquery-rails'
gem 'kaminari'
gem 'ransack'
gem 'simple_form'
gem 'validates_timeliness'
# deployment process management
gem 'foreman'
gem 'thin'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '< 2.0'
gem 'bootstrap-sass', '~> 2.3.1'
end
group :production do
gem 'pg'
end
group :development, :test do
gem 'factory_girl_rails', '~> 4.2.0'
gem 'rspec-rails', '~> 2.13.1'
gem 'spork-rails'
gem 'sqlite3'
end
group :test do
gem 'capybara'
gem 'growl'
gem 'launchy'
gem 'ruby-prof'
gem 'test-unit'
end
spec/spec_helper.rb
require 'rubygems'
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'
Spork.prefork do
# Prevent Devise from loading the User model super early with it's routes
# see: https://github.com/sporkrb/spork/wiki/Spork.trap_method-Jujitsu
require "rails/application"
Spork.trap_method(Rails::Application::RoutesReloader, :reload!)
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# Since I have included Test::Unit for perfomance tests, disable auto-run
Test::Unit::AutoRunner.need_auto_run = false if defined?(Test::Unit::AutoRunner)
# 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 }
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# 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
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
end
Spork.each_run do
# This code will be run each time you run your specs.
end
I'm not getting any error messages or feedback on the console, so I don't even know where to start looking for problems. Any suggestions?
Upgrading ruby-build via brew update ruby-build picked up a new version dated 2013-05-01. After the update, I trashed and reinstalled all my Rubies, and the problem seems to have resolved itself.
I don't know what specifically addressed the issue, but here are some notes and a relevant commit: https://github.com/sstephenson/ruby-build/commit/9f8d53365aef52c940095f583cdc82f02caba90f