I am new to rails and I have an application that is supposed to send a confirmation email after creating a booking however, when I go to the /letter_opener tab after creating a booking nothing shows up
application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "support#flightbooker.com"
layout "mailer"
end
passenger_mailer.rb
class PassengerMailer < ApplicationMailer
def booking_confirmation
#passenger = params[:passenger]
#booking = params[:booking]
#flight = params[:flight]
mail(to: #passenger.email, subject: "Confirmation Email")
end
end
bookings_controller.rb
class BookingsController < ApplicationController
include BookingsHelper
def new
#booking = Booking.new
#selected_flight = Flight.find(params[:flight])
#passengers_count = params[:passengers].to_i
#passengers_count.times{#booking.passengers.build}
end
def create
#booking = Booking.new(booking_params)
if #booking.save
#booking.passengers.each do |pax|
PassengerMailer.with(passenger: pax).booking_confirmation.deliver_now
end
flash[:success] = 'Booking saved!'
redirect_to booking_path(#booking)
else
flash[:alert] = "An error has occured!"
render "new"
end
end
def show
#booking = Booking.find(params[:id])
end
end
Gemfile
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby "3.1.2"
# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.4"
# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"
# Use sqlite3 as the database for Active Record
gem "sqlite3", "~> 1.4"
# Use the Puma web server [https://github.com/puma/puma]
gem "puma", "~> 5.0"
# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"
# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"
# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"
# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"
# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"
# Use Kredis to get higher-level data types in Redis
[https://github.com/rails/kredis]
# gem "kredis"
# Use Active Model has_secure_password
[https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]
# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false
# Use Sass to process CSS
# gem "sassc-rails"
# Use Active Storage variants
[https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"
group :development, :test do
See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-
the-debug-gem
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end
group :development do
# Use console on exceptions pages [https://github.com/rails/web-console]
gem "web-console"
# Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
# gem "rack-mini-profiler"
# Speed up commands on slow machines / big apps [https://github.com/rails/spring]
# gem "spring"
gem 'letter_opener_web'
end
group :test do
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
gem "capybara"
gem "selenium-webdriver"
gem "webdrivers"
end
development.rb
require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable server timing
config.server_timing = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for
options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.perform_deliveries = true
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
# Uncomment if you wish to allow Action Cable access from any origin.
# config.action_cable.disable_request_forgery_protection = true
end
routes.rb
Rails.application.routes.draw do
# Define your application routes per the DSL in
https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
root "flights#index"
resources :flights
resources :airports
resources :bookings
mount LetterOpenerWeb::Engine, at: "/letter_opener" if Rails.env.development?
end
if you still need more code here is a link to my github https://github.com/Michael-Mehta/odin-flight-booker
Related
I'm trying to deploy chatapp on heroku but once I deploy it, ActionCable doesn't work though it works on localhost. I think because redis doesn't connect well on heroku. Could anyone please help?
Error
enter image description here
enter image description here
enter image description here
Gemfile
gem 'rails', '~> 5.2.4', '>= 5.2.4.1'
# Use sqlite3 as the database for Active Record
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
gem 'semantic-ui-sass'
gem 'jquery-rails'
# Use Redis adapter to run Action Cable in production
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
gem 'hirb'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'sqlite3'
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
end
group :production do
gem 'pg', '0.20.0'
gem 'redis'
gem 'redis-rails'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
config/cable.yml
development:
adapter: async
test:
adapter: async
# production:
# adapter: redis
# url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
# channel_prefix: twinz_pfw_2020_production
production:
adapter: redis
url: <%= ENV["REDIS_URL"] %>
config/application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TwinzPfw2020
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.action_cable.mount_path = '/cable'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
config/environments/production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "myrecipes_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_cable.url = 'wss://prayforourworld.herokuapp.com/cable'
config.web_socket_server_url = "wss://prayforourworld.herokuapp.com/cable"
config.action_cable.allowed_request_origins = [ /https?:\/\/.*/ ]
config.action_cable.allowed_request_origins = ['https://prayforourworld.herokuapp.com/', '/http:\/\/prayforourworld.herokuapp.*/']
end
config/initializers/redis.rb
$redis = Redis.new(url: ENV["REDIS_URL"]) if Rails.env.production?
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.
Have factory_girl_rails gem installed, runs fine on local environment, but not on Heroku. It says:
Factory not registered :user.
Any ideas or relevant files I should post for help?
source 'https://rubygems.org'
ruby '2.0.0'
gem 'rails', '4.0.2'
gem 'jbuilder', '~> 1.2'
gem 'jquery-rails'
gem 'turbolinks'
gem 'uglifier', '>= 1.3.0'
# server and database stacks
gem 'pg'
gem 'rails_12factor', group: :production
gem 'thin'
# template and assets stacks
gem 'bootstrap-sass'
gem 'gon'
gem 'jquery-ui-rails'
gem 'sass-rails', '~> 4.0.0'
gem 'slim-rails'
gem 'coffee-rails', '~> 4.0.0'
gem "filepicker-rails", "~> 1.0.0"
gem 'simple_form'
# authentication and authorization stacks
gem 'devise'
gem 'role_model'
# functionality stacks
gem 'state_machine'
gem 'watu_table_builder', :require => 'table_builder'
gem 'factory_girl_rails'
gem 'faker'
group :development do
gem "better_errors"
gem "binding_of_caller"
gem 'pry-rails'
gem 'quiet_assets'
end
group :development, :test do
gem 'coveralls', require: false
gem 'dotenv-rails'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'rb-fchange', require: false
gem 'rb-fsevent', require: false # For Guard file detection on Mac OS X
gem 'rb-inotify', require: false
gem 'rb-readline', require: false
end
group :test do
gem 'capybara'
gem "codeclimate-test-reporter", require: nil
gem 'database_cleaner'
gem 'shoulda-matchers'
gem 'simplecov', require: false
gem 'terminal-notifier-guard' # OSX 10.8
end
group :doc do
gem 'sdoc', require: false
end
and the application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module ApplicationNew
class Application < Rails::Application
# 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.
# 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)'
config.time_zone = 'Singapore'
config.active_record.default_timezone = :local
config.filepicker_rails.api_key = ENV["FILEPICKER_API_KEY"]
# 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
config.i18n.enforce_available_locales = true
config.generators do |g|
g.stylesheets false
g.helper false
g.javascripts false
g.jbuilder false
g.view_specs false
end
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**/}')]
end
end
and production.rb
ApplicationNew::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
It's generally not the best idea to use factory girl in a staging or production environment even just to seed the database. Typically you would include the gem in the test and development groups only so it wouldn't even be installed as part of your heroku deploy.
Great blog post on why this isn't a good idea:
http://robots.thoughtbot.com/factory_girl-for-seed-data
couple of days ago i noticed that jquery calendar is not working on my deployment site(heroku). on digging out the problem i noticed that source of site on my dev server has some 100 script tags related to bootstrap(i am using twitter bootstrap css) but on prod server. i have 4 script tags. on searching i found that i should run rake assets:precompile on my rails console fo asset pipeline. but while running it is taking terribly long time, last time it took 6 hours and i had to abort it.
referring to many sites and post, i found that i should change config.serve_static_assetsto true and config.assets.compile to true. but problem is still there. i also tried to remove jquery-rails/jquery-ui-rails from gembut problem is still there.
here is my config/environmnets/production.rb
ProductRecall::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.action_controller.perform_caching = false
end
my config/application.rb looks like this
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module ProductRecall
class Application < Rails::Application
# 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 += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.action_mailer.default_url_options = { host: 'localhost:3000' }
end
end
here is my Gem file:
source 'https://rubygems.org'
gem 'rails', '3.2.13'
gem 'bootstrap-sass', '2.1'
gem 'bcrypt-ruby', '3.0.1'
gem 'therubyracer', :platforms => :ruby, :platforms => :ruby
gem 'faker', '1.0.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.6'
gem 'bootstrap-datepicker-rails'
gem "google_visualr", "~> 2.1.0"
gem 'twitter-bootstrap-rails'
gem "galetahub-simple_captcha", :require => "simple_captcha"
gem 'rufus-scheduler'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
end
group :development do
gem 'annotate', '2.5.0'
end
group :assets do
gem 'sass-rails', '3.2.5'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
gem 'jquery-rails', '2.0.2'
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails', '4.1.0'
gem 'cucumber-rails', '1.2.1', :require => false
gem 'database_cleaner', '0.7.0'
end
#gem 'jquery-ui-rails'
group :production do
gem 'pg', '0.12.2'
end
plz let me know what is wrong here. as i am terribly stuck with no clue since 2 days
I had also faced the same problem. Actually gem gets conflict. Here 'rufus-scheduler' gem is the culprit. Try to remove the gem and deploy.
Next you can try this
task :precompile, :roles => :web, :except => { :no_release => true } do
run_locally("rm -rf public/assets/*")
run_locally("bundle exec rake assets:precompile")
servers = find_servers_for_task(current_task)
port_option = port ? " -e 'ssh -p #{port}' " : ''
servers.each do |server|
run_locally("rsync --recursive --times --rsh=ssh --compress --
human-readable #{port_option} --progress public/assets #{user} ##{server}: {shared_path}")
end
end
I make a folder in public/images called google-markers but when i go to
http://myproject/images/google-markers/mymarker.png
I got this error :
No route matches "/images/google-markers/mymarker.png"
It seems, i can't use a subfolder of images in my project. When i use direct images in my images folder, everything works fine.
Thank you for help!
ps : I use passenger for deployment, it's a development version on rails 3.0.9
EDIT :
My config.ru :
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Hotelandlodge::Application
and my development.rb :
Hotelandlodge::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# 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_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
Paperclip.options[:command_path] = "/usr/local/bin/"
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end
My config/application.rb :
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Hotelandlodge
class Application < Rails::Application
# 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}/extras)
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# 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 += [:password]
end
end
My Gemfile :
source 'http://rubygems.org'
gem 'rails', '3.0.9'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'mysql2', '< 0.3'
gem "paperclip", "~> 2.4"
gem 'activeadmin'
gem 'will_paginate'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
Did you add the path to routes.rb?