I'm using Rollbar for error tracking in my Rails app. For some reason I'm getting errors from my localhost (in development). In config/initializers/rollbar.rb:
unless Rails.env.production?
config.enabled = false
end
Anything else I need to be doing?
Full rollbar.rb file:
Rollbar.configure do |config|
config.access_token = Figaro.env.rollbar_key
# Here we'll disable in 'test':
unless Rails.env.production?
config.enabled = false
end
end
This worked for me. Now you will get notified only when an exception happens in production.
Rollbar.configure do |config|
config.access_token = ENV['ROLLBAR_ACCESS_TOKEN']
if Rails.env.test? || Rails.env.development?
config.enabled = false
end
config.environment = ENV['ROLLBAR_ENV'].presence || Rails.env
end
Related
I am trying to stub the env variable to access Rails.env.production?
context 'Rails environment is production' do
it 'returns the correct api production service' do
allow(ENV).to receive(:[]).with('RAILS_ENV').and_return('production')
expect(application.api_domain).to eql('https://api.some_url.com')
end
end
but I always get this error
NoMethodError:
undefined method `allow' for #<RSpec::ExampleGroups::CesidApplication::CesidApplication::RailsEnvironmentIsDevelopment:0x00007fcc48cec518>
Did you mean? all
Module method im testing
module Cesid
module Application
def api_domain
uri = URI.parse(marketing_suite_url)
domain = PublicSuffix.parse(uri.host)
Rails.env.production? ? "https://api.#{domain.name}" : "https://api-#{domain.name}"
end
end
end
Rspec version
3.5.4
Any ideas?
Configure the expect syntax in spec_helper.rb like:
# spec_helper.rb
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
Then the allow will work
I'm building a Rails 6.0.3.4 backend, React.js frontend app and for some reason my session token is not saving on the production build after working perfectly fine on the development build. I've loosened restrictions on the production build on Heroku (in session_store.rb I tweaked it from requiring a specific domain to all domains). When I log in I have it return the session token data and it is there but it's not saving anything (tried multiple browsers/computers). On my react front end I do have {withCredentials: true} in my login/sign up components.
session_store.rb
if Rails.env.production?
Rails.application.config.session_store :cookie_store, key: '_10-athletes', domain: :all
else
Rails.application.config.session_store :cookie_store, key: '_10-athletes'
end
In my sessions_controller.rb
def create
#user = User.find_by(email: session_params[:usernameOrEmail])
unless #user
#user = User.find_by(username: session_params[:usernameOrEmail])
end
if #user && #user.authenticate(session_params[:password])
login!
render json: {
logged_in: true,
user: #user,#returns gthe user
session: session, #returns appropriate session info: session_id: 32 digit hex value, user_id: 1
production: Rails.env.production? #returns true, was curious if it was not registering properly
}
else
# working fine
}
end
end
def is_logged_in?
if logged_in? && current_user
# logged_in? is returning false, jumping to else
else
render json: {
session: session[:user_id], #returns null
}
end
end
application_controller.rb
def login!
session[:user_id] = #user.id
end
def logged_in?
!!session[:user_id]
end
config/application.rb
class Application < Rails::Application
config.load_defaults 6.0
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore)
end
config/environments/production.rb
Rails.application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.compile = false
config.active_storage.service = :local
config.force_ssl = true # tested both including this line and not
config.api_only = false #tested both including this line and not
config.log_level = :debug
config.log_tags = [ :request_id ]
config.action_mailer.perform_caching = false
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
config.active_record.dump_schema_after_migration = false
end
Edit: Added in production.rb
Do you have secure cookies enabled as a option? With SSL?
I'm trying to run a simple test on a Ruby on Rails 6.0 application, but I am getting a 403 error.
Alberts-MacBook-Pro:rr albertski$ rails test test/controllers/categories_controller_test.rb
Running via Spring preloader in process 72301
Run options: --seed 53214
# Running:
F
Failure:
CategoriesControllerTest#test_should_get_categories_index [/Users/albertski/Sites/rr/test/controllers/categories_controller_test.rb:10]:
Expected response to be a <2XX: success>, but was a <403: Forbidden>
categories_controller.rb
class CategoriesController < ApplicationController
def index
end
def new
end
def show
end
end
categories_controller_test.rb
require 'test_helper'
class CategoriesControllerTest < ActionDispatch::IntegrationTest
def setup
#category = Category.create(name: "sports")
end
test "should get categories index" do
get categories_path
assert_response :success
end
end
application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_user, :logged_in?
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!!current_user
end
def require_user
if !logged_in?
flash[:danger] = "You must be logged in to perform this action"
redirect_to root_path
end
end
end
config/environments/test.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!
Rails.application.routes.default_url_options[:host] = 'http://localhost:3000'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.hosts << "localhost:3000"
config.cache_classes = false
# 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=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# 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
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
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 did debug get categories_path and it returns /categories. Also, when viewing the /categories path in a browser I don't have any issues; it only happens in the test.
I was able to find the problem by adding byebug to my test, and printing out response which pointed me to the following message:
Blocked host: www.example.com
To allow requests to www.example.com, add the following to your environment configuration:
config.hosts << "www.example.com"
Updating to config.hosts << "www.example.com" fixed the problem.
Also, not sure why I had config.hosts << "localhost:3000" in there in the first place. Removing that line also fixes the issue.
Remove/Comment out any config.hosts << "your-hostname>" in your config/application.rb you may have.
In my case I had my ngrok there.
config.hosts << "2f0c5431228v.ngrok.io"
Make sure to run rspec using RAILS_ENV=test
RAILS_ENV=test rspec
Rspec will run with your development config if RAILS_ENV is not set, which can cause issues like this.
I have a problem testing a functionality that depends of a Singleton class. That class (ERPDao) is a suite with diferent methods that helps application to connect with external ERP vía REST services using Faraday gem. URLMaker is a helper class for build requests strings. When i try to run a feature spec that depends of one of this methods i have the following message in rspec:
Failure/Error: result = ERPDao.instance.get_credit_info(erp_id)
NoMethodError:
undefined method `instance' for ERPDao:Class
Did you mean? instance_of?
Did you mean? instance_of?
My class ERPDao
class ERPDao
def initialize
#end_points = EndPoint.first
#connection = Faraday.new(:url => #end_points.url_base, request: {
open_timeout: 10, # opening a connection
timeout: 10 # waiting for response
})
end
##instance = ERPDao.new
def self.instance
return ##instance
end
def get_credit_info(erp_id)
begin
return #connection.get URLMaker.instance.get_uri('credit_info', erp_id)
rescue Faraday::Error::ConnectionFailed => e
puts "Connection failed: #{e}"
return 0, false, 0
end
end
...
end
My rails_helper.rb
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'
require 'support/wait_for_ajax'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.before :suite do
DatabaseCleaner.strategy = :truncation
end
config.before :each do
DatabaseCleaner.clean
end
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include Warden::Test::Helpers
config.include Devise::TestHelpers, type: :controller
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
Capybara.javascript_driver = :webkit
Capybara::Webkit.configure do |config|
config.debug = false
config.allow_unknown_urls
config.skip_image_loading
config.timeout = 15
config.raise_javascript_errors = false
end
end
My version of rails is 4.2.6, ruby 2.3.1, factory_bot 4.8.2 and rspec-rails 3.7.
Someone knows about this error?
Thanks!
ERPDao is [also] being defined somewhere else. Maybe someone decided to add a method to it by re-opening the class like
class ERPDao
def some_new_method
...
end
end
Don't do that. Use modules and prepend instead.
module HasMyNewMethod
def some_new_method
...
end
end
ERPDau.prepend HasMyNewMethod
Otherwise you end up accidentally referencing the re-opening of the class and that becomes the definition - so the autoloader doesn't load it since it's already defined.
Search your codebase for 'class ERPDao'. Modify the ones that are not the initial declaration.
I've got a Rails 3.2.21 app on Ruby 2.1.5 that uses Postgres, Redis as the cache store (config.cache_store = :redis_store), background workers (mostly for view cache warming) with sidekiq. Russian doll caching used with the cache_digests gem so you end up with cache keys like views/my_lovely_partial/5506949e3754753ad58190924d5b029f. Running tests with RSpec, Factory Girl and Capybara.
For the test environment I have set up a parallel Redis server, different port to production and dev, and have "config.action_controller.perform_caching = true" in test rb. It's the same redis setup in dev and test apart from the port being different.
Testing through either controller spec or feature spec I see the presence of objects cached in Redis, either through the tests themselves or directly viewing the keys in redis-cli.
When I try to test for view partials in Redis I find they are not being cached e.g. In dev environment on the same machine the view partials appear in the redis cache whereas in test they don't - only cached objects appear; this is confirmed by viewing through the redis-cli for both dev and test redis instances. 'render_template' and 'have_content' together with viewing the tested page (Using the 'capybara-screenshot' gem) confirm the content is being served successfully but the partials are not being cached in test.
Gems used specifically in test : rspec-rails, factory_girl_rails, faker, capybara, capybara-screenshot, capybara-user_agent, pry, guard-rspec, launchy, database_cleaner, shoulda-matchers, redis, turn.
I've checked in the spec.rb's that perform_caching is still true; tried temporarily removing pry, guard-rspec, launchy, shoulda-matchers gems but no difference. Tried removing database_cleaner gem, disabling all test cache clearing and ran tests again to find only object caching present in redis, no partials.
test.rb
SmashingSuperApp::Application.configure do
config.cache_classes = true
config.whiny_nils = true
config.consider_all_requests_local = false
config.action_dispatch.show_exceptions = true
config.action_controller.allow_forgery_protection = false
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
config.action_controller.perform_caching = true
config.cache_store = :redis_store, "redis://localhost:6378/0/cache", { expires_in: 1176.hours }
ENV["REDIS_URL"] ||= "redis://localhost:6378/0"
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.action_dispatch.best_standards_support = :builtin
config.active_record.mass_assignment_sanitizer = :strict
config.active_record.auto_explain_threshold_in_seconds = 0.5
config.log_tags = [:uuid, :remote_ip]
config.before_initialize do |app|
app.config.paths.add 'app/models', :eager_load => true
end
config.to_prepare do
Dir["#{Rails.root}/app/models/*"].each do |model_name|
require_dependency model_name unless model_name == "." || model_name == ".."
end
end
Rails.application.routes.default_url_options[:host]= 'smashingsuperapp.co.uk:3000'
end
rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara-screenshot/rspec'
require 'shoulda/matchers'
require 'faker'
require 'redis'
RSpec.configure do |config|
config.include Rails.application.routes.url_helpers
config.infer_spec_type_from_file_location!
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
Rails.cache.clear # Clear redis cache
end
config.before(:each) do |example|
DatabaseCleaner.strategy= example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
Rails.cache.clear # Clear redis cache
end
config.include FactoryGirl::Syntax::Methods
config.after do |example|
if example.metadata[:type] == :feature and example.exception.present?
save_and_open_page
end
end
end
def set_host (host)
default_url_options[:host] = host
Capybara.app_host = "http://" + host
end
spec_helper.rb
require 'capybara/user_agent'
Capybara::UserAgent.add_user_agents(mechanize: 'Mechanize')
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.include Capybara::UserAgent::DSL
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
=begin
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
=end
end
def get_path(path)
parsed_params = Rails.application.routes.recognize_path path
controller = parsed_params.delete(:controller)
action = parsed_params.delete(:action)
get(action, parsed_params)
end
Feature specs use 'visit' and controller specs use 'get' to the correct URL's and render the correct content.
Any pointers as to why partials wouldn't be being cached in this situation very much appreciated. Thanks in advance.
Thought I'd try adding the 'selenium-webdriver' gem and after lots of irony debugging/trial/error in the test environment I then found cached partials were appearing in Redis.
In case it helps others as I found a information a bit patchy;
Further added
gem 'selenium-webdriver'
into test group of Gem file.
Modified /spec/rails_helper.rb below. Note particularly Capybara.server_port = 10000, Capybara.always_include_port = true, Capybara.javascript_driver = :selenium - default port was not being picked up in js marked tests so had to lock it down there.
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara-screenshot/rspec'
require "rack_session_access/capybara"
require 'shoulda/matchers'
require 'faker'
require 'redis'
require 'support/wait_for_ajax'
RSpec.configure do |config|
config.include Rails.application.routes.url_helpers
config.infer_spec_type_from_file_location!
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
Rails.cache.clear # Clear redis cache
# To prevent FactoryGirl creating persons with an id that are reserved for 'special' persons
ActiveRecord::Base.connection.execute("ALTER SEQUENCE persons_id_seq START with 4000 RESTART;")
end
config.before(:each) do |example|
DatabaseCleaner.strategy= example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
Rails.cache.clear # Clear redis cache
end
config.include FactoryGirl::Syntax::Methods
config.after do |example|
if example.metadata[:type] == :feature and example.exception.present?
save_and_open_page
end
end
end
Capybara.server_port = 10000
Capybara.always_include_port = true
Capybara.javascript_driver = :selenium
def set_host (host)
# host! host
default_url_options[:host] = host
Capybara.app_host = "http://" + host
end
The "require 'support/wait_for_ajax'" in the above, described here, is something I came across whilst trying to get selenium up and running that looks handy for ajax testing. Although ajax was not playing a role in the cached partials I was testing for this, there are others with ajax calls where this would be handy.
For the feature tests using selenium, have those tests in their own describe block e.g.
describe "special person accesses event with JS tests" do
before(:each) do
Capybara.current_driver = :selenium
end
after(:all) do
Capybara.use_default_driver
end
scenario 'can view persons partial with cache insertion', js: true do
visit some_cached_page_path(id:some_page_id)
...
And then any following tests that use rack_test (default no full browser and no js tests) put them in a separate describe block but without 'js: true' and those before and after blocks. Initially I thought I would only need to mark selenium driven test blocks with "js: true" but found issues then with the basic rack_test based blocks until I took the above describe block approach.