The ActionMailer in my Rails 3.1 project has an odd behavior, the ActionMailer::Base.deliveries is empty in test while I can actually receive the email by running the code in rails console. Anybody can points out what wrong it is?
# spec/mailers/user_mailer_spec.rb
require "spec_helper"
describe UserMailer do
describe ".reminding_email" do
subject { UserMailer.reminding_email(user).deliver }
let(:user) { create :confirmed_user_with_mass_tasks }
it "should be delivered" do
ActionMailer::Base.deliveries.should_not be_empty
end
its(:to) { should == [user.email] }
its(:subject) { should == "Task Reminding" }
end
end
# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
layout "email"
default from: Rails.env.production? ? "<production>#gmail.com" : "<test>#gmail.com"
def reminding_email(user)
#tasks = user.tasks.reminding_required
#current = Time.current
mail(to: user.email, subject: "Task Reminding")
end
end
Failures:
1) UserMailer.reminding_email should be delivered
Failure/Error: ActionMailer::Base.deliveries.should_not be_empty
expected empty? to return false, got true
# ./spec/mailers/user_mailer_spec.rb:8:in `block (3 levels) in '
Finished in 11.81 seconds
42 examples, 1 failure, 2 pending
# config/environments/test.rb
RemindersForMe::Application.configure do
# Settings specified here will take precedence over those in config/application.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
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# 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
# 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
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
# Setup default URL options as devise needed
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
Application:
# config/application.rb
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)))
Bundler.require *Rails.groups(:assets) if defined?(Bundler)
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module RemindersForMe
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
# 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 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'
# Set Rspec generator as default
config.generators do |g|
g.test_framework :rspec
end
# Set Mailer of Devise
config.to_prepare do
Devise::Mailer.layout "email"
end
end
end
Now change the spec as follow:
require "spec_helper"
describe UserMailer do
describe ".reminding_email" do
subject { UserMailer.reminding_email(user) }
let(:user) { create :confirmed_user_with_undue_tasks }
it { expect { subject.deliver }.to change { ActionMailer::Base.deliveries.length }.by(1) }
its(:to) { should == [user.email] }
its(:subject) { should == "Task Reminding" }
end
end
1) UserMailer.reminding_email
Failure/Error: it { expect { subject.deliver }.to change { ActionMailer::Base.deliveries.length }.by(1) }
result should have been changed by 1, but was changed by 2
# ./spec/mailers/user_mailer_spec.rb:7:in `block (3 levels) in '
I had a similar problem and it happened because I was testing Devise emails: Devise uses a separate mailer, so you'll need to access Devise.mailer.deliveries instead of ActionMailer::Base.deliveries.
You should test the separated properties of the mail:
describe UserMailer do
describe ".reminding_email" do
subject { UserMailer.reminding_email(user)}
let(:user) { create :confirmed_user_with_mass_tasks }
it{ expect{subject.deliver}.to change{ActionMailer::Base.deliveries.length}.by(1)}
its(:to) { should == [user.email] }
its(:subject) { should == "Task Reminding" }
end
end
Notice the change in the subject, because your mailer as it should returns the mail method result, which already initialized with to and subject.
By default Action Mailer does not send emails in the test environment. They are just added to the ActionMailer::Base.deliveries array. (See section 6 in http://guides.rubyonrails.org/action_mailer_basics.html)
What "by default" means is that you should not provide effective email_delivery settings for the test environment. If there are effective default email_delivery settings in "config/configuration.yml", you can override it with:
test:
email_delivery:
delivery_method: :test
How are you configuring ActionMailer? Is it within your config/application.rb file or within the specific environments/*.rb files?
Remember, anything you specify in the environments/*.rb files take precedence over the config/application.rb file.
So perhaps your problem is that when running in test mode the ActionMailer is using :smtp and not :test?
Related
I'm using Rails 5. I have this file, config/environment_variables.yml
development:
COINBASE_KEY: devkey
COINBASE_SECRET: devsecret
test:
COINBASE_KEY: testkey
COINBASE_SECRET: testsecret
production:
COINBASE_KEY: prodkey
COINBASE_SECRET: prodsecret
I load it with the file, config/initializers/environment_variables.rb
module EnvironmentVariables
class Application < Rails::Application
config.before_configuration do
env_file = Rails.root.join("config", 'environment_variables.yml').to_s
if File.exists?(env_file)
YAML.load_file(env_file)[Rails.env].each do |key, value|
ENV[key.to_s] = value
end # end YAML.load_file
end # end if File.exists?
end # end config.before_configuration
end # end class
end # end module
but when I run my test using
rails test test/services/crypto_currency_service_test.rb
The test variables aren't loading -- rather those from the dev environment are loading. Below is my test file
require 'coinbase/wallet'
require 'minitest/mock'
class CryptoCurrencyServiceTest < ActiveSupport::TestCase
test 'sell' do
last_transaction = MyTransaction.new({
:transaction_type => "buy",
:amount_in_usd => "100",
:btc_price_in_usd => "3000"
})
puts "env: #{ENV['COINBASE_KEY']}"
#client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
How do I get the test variables to load by default when I run tests?
Edit: Here's the config/environments/test.rb file, which I haven't (consciously) changed ...
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.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
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=3600'
}
# 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
config.action_mailer.perform_caching = 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
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
I would not recommend to write custom code for this. There are existing solutions for setting up environment variables. See dotenv-rails for example. It allows you to put common variables into .env file. Just add gem 'dotenv-rails' to your Gemfile and put common variables into .env file:
# .env
COINBASE_KEY: devkey
COINBASE_SECRET: devsecret
If you need environment-specific variables it allows you to have separate files for this: .env.development, .env.test and .env.production:
#.env.test
COINBASE_KEY: testkey
COINBASE_SECRET: testsecret
#.env.production
COINBASE_KEY: prodkey
COINBASE_SECRET: prodsecret
From the comments in your original post, I suggest checking if config.before_configuration block is not at fault. Might be the case that the rails environment is loaded after that block has run and so you get Rails.env == 'test' when you print that out inside a test, but in the configuration it takes keys from default (development) environment.
Might I suggest moving this part
env_file = Rails.root.join("config", 'environment_variables.yml').to_s
if File.exists?(env_file)
YAML.load_file(env_file)[Rails.env].each do |key, value|
ENV[key.to_s] = value
end # end YAML.load_file
end # end if File.exists?
out in an intializer and then check the environment variables. Might fix the problem. (because initializers surely should respect the environment)
UPDATE: From the documentation it seems that before_configuration block is the VERY first block config part to run, so Rails.env is probably not yet set at that point.
So I'm doing an online bootcamp on codermanual, btw I'm a total beginner and just started learning Ruby and the rest of webdev stuff.
I'm stuck on a certain step and I'm having an issue regarding "receiving emails" from the contact forms page of my webapp via heroku.
For some reason, I can't seem to make sendgrid work.
When I hit submit button of my contact form, webpage returns an error message.
I followed the steps precisely but there seems to be a problem with my contacts_controller.rb particularly this line of code:
ContactMailer.contact_email(name, email, body).deliver
ruby v2.3.0p0
$heroku logs
ArgumentError (An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.):
2016-06-13T05:24:00.381485+00:00 app[web.1]: app/controllers/contacts_controller.rb:14:in `create'
Appreciate the help.
Here are the rest of the files:
controllers/contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(contact_params)
if #contact.save
name = params[:contact][:name]
email = params[:contact][:email]
body = params[:contact][:comments]
ContactMailer.contact_email(name, email, body).deliver
flash[:success] = 'Message sent.'
redirect_to new_contact_path
else
flash[:danger] = 'Error occured, message has not been sent'
redirect_to new_contact_path
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
config/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(*Rails.groups)
module SimplecodecastsSaas
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)'
# 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
end
end
views/contact_mailer/contact_email.html.erb
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>You have received a message from the site's contact form, from <%= "#{ #name }, #{ #email }." %></p>
<p><%= #body %></p>
</body>
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
# 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 cannot 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
environments/development.rb
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 on
# every request. 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
#a fix for circular dependency while autoloading constant.
#config.middleware.delete Rack::Lock
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = 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
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
apps/mailers/contact_mailer.rb
class ContactMailer < ActionMailer::Base
default to: "jxxmxlmxo#gmail.com"
def contact_email(name, email, body)
#name = name
#email = email
#body = body
mail(from: email, subject: 'Contact Form Message')
end
end
I'm fairly new to Ruby on Rails and making my way through Michael Hartl's Rails Tutorial. I've hit a bug I can't seem to fix on Chapter 10 (specifically, 10.1.3 "User/Micropost associations"). The error I run into is when I execute the following rspec command:
$ bundle exec rspec spec/models
It raises the following error:
Failures:
1) Micropost accessible attributes should not allow access to user_id
←[31mFailure/Error:←[0m ←[31mexpect do←[0m
←[31mexpected ActiveModel::MassAssignmentSecurity::Error but nothing was
raised←[0m
←[36m # ./spec/models/micropost_spec.rb:28:in `block (3 levels) in <top (req
uired)>'←[0m
Finished in 5.79 seconds
←[31m27 examples, 1 failure←[0m
Failed examples:
←[31mrspec ./spec/models/micropost_spec.rb:27←[0m ←[36m# Micropost accessible at
tributes should not allow access to user_id←[0m
This is the code for micropost_spec.rb:
require 'spec_helper'
describe Micropost do
let(:user) { FactoryGirl.create(:user) }
before { #micropost = user.microposts.build(content: "Lorem ipsum") }
subject { #micropost }
it { should respond_to(:content) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
its(:user) { should == user }
it { should be_valid }
describe "when user_id is not present" do
before { #micropost.user_id = nil }
it { should_not be_valid }
end
describe "accessible attributes" do
it "should not allow access to user_id" do
expect do
Micropost.new(user_id: user.id)
end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
end
application.rb:
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 SampleApp
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.
config.active_record.whitelist_attributes = true
# 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
# 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 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'
end
end
micropost.rb...
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :user_id, presence: true
end
Thanks in advance for your help!
Thai
So expected ActiveModel::MassAssignmentSecurity::Error but nothing was
raised when Micropost.new(user_id: user.id) is called.
For it to work correctly:
The Rails application should be configured to explicitly whitelist or blacklist accessible parameters; in rails versions before 3.2.3 this was on by default; in previous versions, it has to be done by the following line in config/application.rb as detailed in Listing 10.6 of RailsTutorial book:
config.active_record.whitelist_attributes = true
There shouldn't be a attr_accessible :user_id in the micropost.rb model file.
Try adding
config.active_record.mass_assignment_sanitizer = :strict
To your application.rb file, what I found out is that if not strict, it would just throw a Warning but not an exception.
Like you, I tried all of the solutions above with no luck. I also notice that Hartl's more recent editions of the book for Rails 4 do not contain those tests, so I suspect this approach to testing accessibility does not work in later versions. Perhaps an expert (someone who isn't running through the Rails Tutorial) can chime in.
But.... I noticed this response in another StackOverflow thread recommending the "shoulda-matchers" Gem to test it, and that solved the problem for me (https://stackoverflow.com/a/11876425/3899955). In investigating that Gem, I find it is a nice way to produce readable tests for a number of common ActiveModel, ActiveRecord, and ActionController tests. I am happy to be adding that to my quiver, perhaps you will be too.
I don't take credit for that answer, just wanted to post this so if anyone else is running in to this frustration doing Chapter 10.5, or completing exercise 6 in Chapter 9.
using devise 2.1.0
I had to override the devise registration controller. In the process I had to move my devise views directory to correspond with the new controller. I have this code in my config/applications.rb file
paths.app.views << "app/views/devise"
And it is throwing an error when I try and start my server with rails s:
...config/application.rb:65:in `<class:Application>': undefined method `app' for #<Rails::Paths::Root:0x00000103537740> (NoMethodError)
I am relatively new at rails. But I get that there is a root class somewhere that didn't define app. I got this advice to use this paths.app.views here at stack.
Here is the full applications.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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 Growle
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
# 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, :password_confirmation]
#don't generate RSpec tests for views and helper
config.generators do |g|
g.view_specs false
g.helper_specs false
end
# Use SQL instead of Active Record's schema dumper when creating the 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
# 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'
paths.app.views << "app/views/devise"
end
end
By reading the last comment of yours, it sound that you want either view_paths= or prepend_view_path.
Those can be set at class level in your controller.
If that isn't what you are looking for, consider reading Override devise registrations controller for information.
Releated to this: Rake on Rails 3 problem
I'm trying to copy a rake task working under rails 2, into a rails 3 app.
The rake task is the following:
namespace :cached_assets do
desc "Regenerate aggregate/cached files"
task :regenerate => :environment do
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::AssetTagHelper
stylesheet_link_tag :all, :cache => CACHE_CSS_JS
javascript_include_tag "a.js", "b.js",
"c.js", :defaults, :cache => CACHE_CSS_JS
javascript_include_tag "q.js", "w.js",
"e.js", :cache => 'abc'
end
end
On Rails 2 it cache the assets correctly, on rails 3 I have the following error:
rake cached_assets:regenerate --trace
(in /var/www/apps/****)
** Invoke cached_assets:regenerate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute cached_assets:regenerate
rake aborted!
undefined local variable or method `config' for #<Object:0xa86290>
/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/actionpack-3.0.3/lib/action_view/helpers/asset_tag_helper.rb:498:in `stylesheet_link_tag'
/var/www/apps/****/lib/tasks/cached_assets.rake:10
/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
Looking at the definition of stylesheet_link_tag I see:
def stylesheet_link_tag(*sources)
options = sources.extract_options!.stringify_keys
concat = options.delete("concat")
cache = concat || options.delete("cache")
recursive = options.delete("recursive")
if concat || (config.perform_caching && cache)
joined_stylesheet_name = (cache == true ? "all" : cache) + ".css"
joined_stylesheet_path = File.join(joined_stylesheet_name ......
..... ....
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 ****
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]
config.time_zone = 'UTC'
# 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}')]
# config.i18n.default_locale = :de
# use memcache
config.cache_store = :mem_cache_store, 'localhost:11211', { :namespace => 'nar_' }
config.after_initialize do
require 'lib/core_extensions.rb'
end
end
end
My config/environments/development.rb:
****::Application.configure do
# Settings specified here will take precedence over those in config/environment.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.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# EMAIL -> see also initializers/emailer_initializers.rb and /config/email.yml !!!!!!!!!!!!
EMAIL_ENABLED = false
config.action_mailer.raise_delivery_errors = true
MAIL_FROM = '****'
RCPT_TO_DEV = '****'
ENV['RAILS_ASSET_ID'] = '100'
PRODUCTION_DOMAIN_NAME = "*****"
#CSS CACHING
CACHE_CSS_JS = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end
I had the same problem and found a solution here: http://railsforum.com/viewtopic.php?id=42282
Just prefix
stylesheet_link_tag
and
javascript_include_tag
with
ApplicationController.helpers.
then you shouldn't even have to include the ActionView helpers.