discrepancy between requiring a path in rails console vs. rails s (WeBRICK) - ruby-on-rails

I'm using Machinist blueprints in development.
from development.rb:
config.after_initialize do
require 'spec/support/blueprints'
puts "********* blueprints loaded! *********"
end
it works fine in the console.
michael-schwabs-macbook-pro:medtext mschwab$ rails c
********* blueprints loaded! *********
Loading development environment (Rails 3.0.7)
irb(main):001:0> d = Doctor.make
=> #<Doctor id: 101, first_name: nil, ....
When I run the server, my controllers know that my models respond to #make, but they don't know that the blueprints are defined.
(rdb:70) Doctor.respond_to?(:make)
true
(rdb:70) Doctor.make
RuntimeError Exception: No blueprint for class Doctor
This is odd because the statement
require 'machinist/active_record'
is in the blueprints.rb file. Also, the "loaded!" statement gets printed out in my server log.
=> Ctrl-C to shutdown server
********* blueprints loaded! *********
=> Debugger enabled

Related

Running webpacker:compile for a engine in my host app causes rails to abort

I have a rails engine/plugin in which i am trying to use webpacker using THIS article as a guide. So basically in my engine, i have the following code :-
lib/saddlebag.rb
require "saddlebag/engine"
module Saddlebag
# ...
class << self
def Webpacker
#Webpacker ||= ::Webpacker::Instance.new(
root_path: Saddlebag::Engine.root,
config_path: Saddlebag::Engine.root.join('config', 'webpacker.yml')
)
end
end
# ...
end
and in the lib/saddlebag/engine.rb file i have the following code :
module Saddlebag
class Engine < ::Rails::Engine
isolate_namespace Saddlebag
# use packs from saddlebag via Rack static
# file service, to enable webpacker to find them
# when running in the host application
config.app_middleware.use(
Rack::Static,
# note! this varies from the webpacker/engine documentation
urls: ["/saddlebag-packs"], root: Saddlebag::Engine.root.join("public")
)
initializer "webpacker.proxy" do |app|
insert_middleware = begin
Saddlebag.webpacker.config.dev_server.present?
rescue
nil
end
next unless insert_middleware
app.middleware.insert_before(
0, Webpacker::DevServerProxy, # "Webpacker::DevServerProxy" if Rails version < 5
ssl_verify_none: true,
webpacker: Saddlebag.webpacker
)
end
end
end
Also i have all of the files required by webpacker mainly :-
config/webpacker.yml and config/webpack/*.js files
bin/webpack and bin/webpack-dev-server files
package.json with required deps.
So the engine and my actually app are in sibling directories so:-
saddlebag
open-flights (main app)
in open flights i link saddlebag with the following line in the gem file :-
gem 'saddlebag', path: '../saddlebag'
Now when i run bin/rails saddlebag:webpacker:compile , i get the following error :-
rails aborted! Don't know how to build task
'saddlebag:webpacker:compile' (See the list of available tasks with
rails --tasks)
Why am i getting this error i have webpacker as a dependency in my saddlebag app. So not sure why this error still occures.
P.S. I found a similar guide for rails engine for enabling webpacker HERE (but uses docker)

PG::UnableToSend: no connection to the server in Rails

I have a production server running ubuntu 14.04, Rails 4.2.0, postgresql 9.6.1 with gem pg 0.21.0/0.20.0. In last few days, there is constantly error with accessing to a table customer_input_datax_records in psql server.
D, [2017-07-20T18:08:39.166897 #1244] DEBUG -- : CustomerInputDatax::Record Load (0.1ms) SELECT "customer_input_datax_records".* FROM "customer_input_datax_records" WHERE ("customer_input_datax_records"."status" != $1) [["status", "email_sent"]]
E, [2017-07-20T18:08:39.166990 #1244] ERROR -- : PG::UnableToSend: no connection to the server
: SELECT "customer_input_datax_records".* FROM "customer_input_datax_records" WHERE ("customer_input_datax_records"."status" != $1)
The code which call to access the db server is with Rufus scheduler 3.4.2 loop:
s = Rufus::Scheduler.singleton
s.every '2m' do
new_signups = CustomerInputDatax::Record.where.not(:status => 'email_sent').all
.......
end
After restart the server, usually there is with first request (or a few). But after some time (ex, 1 or 2 hours), the issue starts to show up. But the app seems running fine (accessing records with read/write & creating new). There are some online posts about the error. However the problem seems not the one I am having. Before I re-install the psql server, I would like to get some ideas about what causes the no connection.
UPDATE: database.yml
production:
adapter: postgresql
encoding: unicode
host: localhost
database: wb_production
pool: 5
username: postgres
password: xxxxxxx
So, the error is "RAILS: PG::UnableToSend: no connection to the server".
That reminds me of Connection pool issue with ActiveRecord objects in rufus-scheduler
You could do
s = Rufus::Scheduler.singleton
s.every '2m' do
ActiveRecord::Base.connection_pool.with_connection do
new_signups = CustomerInputDatax::Record
.where.not(status: 'email_sent')
.all
# ...
end
end
digging
It would be great to know more about the problem.
I'd suggest trying this code:
s = Rufus::Scheduler.singleton
def s.on_error(job, error)
Rails.logger.error(
"err#{error.object_id} rufus-scheduler intercepted #{error.inspect}" +
" in job #{job.inspect}")
error.backtrace.each_with_index do |line, i|
Rails.logger.error(
"err#{error.object_id} #{i}: #{line}")
end
end
s.every '2m' do
new_signups = CustomerInputDatax::Record.where.not(:status => 'email_sent').all
# .......
end
As soon as the problem manifests itself, I'd look for the on_error full output in the Rails log.
This on_error comes from https://github.com/jmettraux/rufus-scheduler#rufusscheduleron_errorjob-error
As we discuss in the comments, the problem seems related to your rufus version.
I would suggest you to check out whenever gem and to invoke a rake task instead of calling directly the activerecord model.
It could be a good idea, however, to open an issue with the traceback of your error in the rufus-scheduler repo on github (just to let then know...)

How to setup error 404 page in Ruby on Rails system testing

Rails 5.1 introduced system testing that uses Capybara with Selenium to test the UI of Rails application.
I'm wondering to how to use this system testing to test the UI of error pages.
For standard controller tests, we can do something like below to assert response to be 404.
test 'should get not_found' do
get errors_not_found_url
assert_response :not_found
end
But for system tests, if I go to a 404 page, exception will be thrown in controller level and tests terminate immediately without rendering the page.
test '404 page should render with the correct title' do
# act.
visit NOT_FOUND_URL
# assert.
assert_equal("#{APP_NAME} - #{TITLE_404}", page.title)
end
Exception is thrown in controller level.
$ rails test test/system/error/error_page_test.rb
Run options: --seed 30076
# Running:
Puma starting in single mode...
* Version 3.9.1 (ruby 2.3.1-p112), codename: Private Caller
* Min threads: 0, max threads: 1
* Environment: test
* Listening on tcp://0.0.0.0:55237
Use Ctrl-C to stop
2017-07-09 11:10:45 +1200: Rack app error handling request { GET /books/12345678 }
#<ActionController::RoutingError: Could not find book '12345678' by id or name>
/myapp/app/controllers/books_controller.rb:7:in `index'
/Users/yze14/.rvm/gems/ruby-2.3.1/gems/actionpack-5.1.2/lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
/Users/yze14/.rvm/gems/ruby-2.3.1/gems/actionpack-5.1.2/lib/abstract_controller/base.rb:186:in `process_action'
...
Under development/test environment, config.consider_all_requests_local can be set to false in order to show error page instead of stracktrace. But this doesn't swallow exception during system tests.
If you don't want Capybara to re-raise server exceptions in the tests you can set Capybara.raise_server_errors = false.
Secondly, you should check your Gemfile and make sure any gems like web-console,better-errrors, etc are only loaded in the development environment (not in the test environment)
Finally, you shouldn't be using assert_equal with title, you should be using the Capybara provided assert_title which includes waiting/retrying behavior and will reduce potential flakiness in tests.
assert_title("#{APP_NAME} - #{TITLE_404}")

RSpec is Freezing

I have rspec configured installed in my rails app. It was working fine (We are just experimenting with rspec so there's only 2 tests).
They were working fine. Now rspec is freezing when it's going to perform a test using database.
I just freezes. I don't even know were to start looking because there's no error in the output.
Is there a verbose or debugging mode for rspec or someone ever faced this?
I've tried -b but it freezes before can give an error.
Output: (Rspec is configured with --format documentation)
[leandro#machine:~] rspec
User
Than, that's it. It hangs. I has to reset manually the computer twice.
This is the user_spec.rb
require 'spec_helper'
describe User do
let(:user) { User.create({
username: "teste",
email: "teste#teste.com",
name: "Teste",
phone: "123456789",
password: "123456",
notes: "Teste"
}) }
subject { user }
it "is invalid without a username" do
user.username = nil
is_expected.not_to be_valid
end
end
And my spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.color = true
config.tty = true
config.formatter = :documentation #:progress, :html, :textmate
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
SOLUTION
It turns out that delayed_job_active_record gem was causing the hanging.
I don't know why, but as #Greg Malcolm I looked into the log/teste.log and rspec was feeezing right after createing the delayed jobs database and setting up a new user.
I've restricted the gem just for development and production enviroment, and it worked!
I haven't heard of a rake like verbose feature for rspec. But it's probably more useful to look through log/test.log and see what shows up there. It shows database activity which is part of a freeze effect.
You might also want to rails console into test and make sure your database connection is working right.
You have to check the ./log/test.log file. As this file tends to grow big, use the tail command to read the last n lines.
For example, to read the last 5 lines of the log file, execute the following command:
tail -5 ./log/test.log
In my case, my Google Pub/Sub emulator was hanging.
[ActiveJob] Failing with status #<struct Struct::Status code=4, details="Deadline Exceeded", metadata={}>
[ActiveJob] calling pubsub.googleapis.com:443:/google.pubsub.v1.Publisher/GetTopic
It might also be helpful to use tail -f ./log/test.log, to keep track of the logs while RSpec is running. You can read more about it on "Tail Your Test Logs", by thoughtbot.
It's pretty old question but in case anybody else will get this. I've got the same strange Rspec behaviour today because of left --drb option in project .rspec file after removing DRb server (spork or zeus). Just make sure Rspec have DRb disabled if you don't have spork or zeus installed.

Redis publish in rails 4 stops server thread

Sorry for english, i'm newbie.
Trying to use redis.publish feature with rails 4 and redis gem to push messages with SSE.
I have this block in my controller
logger.info "test1"
$redis.publish "user", "test"
logger.info "test2"
where $redis -
$redis = Redis.new(:host => '127.0.0.1', :port => 6379, :db => 1,:timeout => 0)
in initializer.
Server console in production print
I, [2013-08-07T22:34:50.138232 #4679] INFO -- : test1
And then nothing. Another request working, but this thread stops.
By the way, this $redis.publish "user", "test" at RAILS_ENV=production rails console run perfectly and message successfully appear at client.
Can you help me?
UPD: Ruby 2.0-p247, Rails 4, Redis 3.0.4
Don't use one connection in initializer to subscribe and publish both.
I created 2 connections, 1 for subscribe in sse writer, 1 in controllers to publish, and everything working normally.

Resources