Rails system test cannot access location of browser - ruby-on-rails

Upon running a system test, the following error is documented:
.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/webdrivers-4.4.1/lib/webdrivers/chrome_finder.rb:21:in `location': Failed to find Chrome binary. (Webdrivers::BrowserNotFound)
Examining the chrome_finder.rb file, location method:
chrome_bin = user_defined_location || send("#{System.platform}_location")
return chrome_bin unless chrome_bin.nil?
raise BrowserNotFound, 'Failed to find Chrome binary.'
thus chrome_bin is not being populated either by the system.platform_location nor a user defined location.
The user_defined_location method implies setting Selenium::WebDriver::Chrome.path
def user_defined_location
if Selenium::WebDriver::Chrome.path
Webdrivers.logger.debug "Selenium::WebDriver::Chrome.path: #{Selenium::WebDriver::Chrome.path}"
return Selenium::WebDriver::Chrome.path
end
return if ENV['WD_CHROME_PATH'].nil?
Webdrivers.logger.debug "WD_CHROME_PATH: #{ENV['WD_CHROME_PATH']}"
ENV['WD_CHROME_PATH']
end
How can this be achieved for this rails application?

Related

Why am I getting Listen Loop Bad File Descriptor errors on my machine but not anyone else's machine when specific code is enabled?

I'm currently working on a project to enable database backed configurations in the frontend of our application. These need to be loaded after application initialization, so I created a module to load them and added a call to it in environment.rb, after Rails.application.initialize!.
The problem is that when this code is enabled, my console gets flooded with listen loop errors with bad file descriptors like:
2020-01-24 09:18:16 -0500: Listen loop error: #<Errno::EBADF: Bad file descriptor>
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:383:in `select'
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:383:in `handle_servers'
/Users/fionadurgin/.asdf/installs/ruby/2.6.5/lib/ruby/gems/2.6.0/gems/puma-4.3.1/lib/puma/server.rb:356:in `block in run'
When I disable either the call to the ConfigurationLoader or the methods I'm calling on the model, I no longer get these errors.
The rub is that I can't reproduce this issue on another machine, or in specs. I've tried on two other laptops and on one of our staging servers and they work perfectly with the ConfigurationLoader enabled.
I've tried restarting my computer, working from a freshly cloned repository, and setting all the file permissions for the application to 777. Nothing has worked so far.
Here's the ConfigurationLoader module:
module ConfigurationLoader
# Overrides client default configurations if frontend configurations exist
def self.call
Configurations::ImportRowMapping.override_configurations
rescue ActiveRecord::NoDatabaseError => e
log_no_database_error(e)
rescue ActiveRecord::StatementInvalid => e
log_statement_invalid_error(e)
rescue Mysql2::Error::ConnectionError => e
log_connection_error(e)
end
def self.log_no_database_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, database does '\
'not exist'
)
Rails.logger.warn(error.message)
end
def self.log_statement_invalid_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, table does '\
'not exist'
)
Rails.logger.warn(error.message)
end
def self.log_connection_error(error)
Rails.logger.warn(
'Could not initialize database backed configurations, could not '\
'connect to database'
)
Rails.logger.warn(error.message)
end
end
The call in environment.rb:
# Load the Rails application.
require_relative 'application'
require_relative 'configuration_loader'
# Initialize the Rails application.
Rails.application.initialize!
ConfigurationLoader.call
And the model method being called:
def self.override_configurations
return unless any?
Rails.application.client.payroll_service_file.payroll_service_file
.mappings = all.to_a
end
I'll note here that I get the errors when either the guard clause or the assignment are enabled.
Anyone have any ideas about what's going on? I'm about at my wits' end.
So I'm still not sure on the exact cause of the problem, but the solution was to move the configuration loader call out of environment.rb and into an after_initialize block in application.rb.

RoR - Validate string on website, no error

In my Ruby on Rails app I have build a function to validate if a piece of javascript is added to a certain website. When I run this code I don't get any errors in my log, but my app says:
We're sorry, but something went wrong.
If you are the application owner check the logs for more information.
But when I check the logs I don't see any errors. The code I have used is the following:
def validate_installation
data = HTTParty.get(self.website)
url = "http://www.smartnotif.com/sn.js"
if data.body.include? url
return true
else
return false
end
end
When I run this code on my local development machine it runs fine, but when I try to runs this production machine on DigitalOcean I have this problem with the same code, no errors.
Try to include
require 'httparty'
Restart rails server
rails s
Also check the permission of log folder, why it is not writing error in log folder
Also try: Use self keyword as you are calling it as class method
def self.validate_installation
data = HTTParty.get(self.website)
url = "http://www.smartnotif.com/sn.js"
if data.body.include? url
return true
else
return false
end
end

Stubbing instance method for OpenTok object

The gem I'm using to integrate OpenTok in my Rails application is at: https://github.com/opentok/Opentok-Ruby-SDK. I based the core of the application on this example: http://www.tokbox.com/blog/building-a-video-party-app-with-ruby-on-rails.
In the relevant part of code, I'm creating an #opentok object in the config_opentok method:
def config_opentok
if #api_key.nil? or #api_secret.nil?
if Rails.env.development?
#api_key = API_KEY
#api_secret = API_SECRET
else
#api_key = ENV['API_KEY']
#api_secret = ENV['API_SECRET']
end
end
if #opentok.nil?
#opentok = OpenTok::OpenTokSDK.new(#api_key, #api_secret)
end
end
And I'm creating a session with the following code:
config_opentok
if Rails.env.development?
session = #opentok.create_session('localhost')
else
session = #opentok.create_session(request.remote_addr)
end
The trouble is, the create_session seems to throw an error
SocketError: getaddrinfo: nodename nor servname provided, or not known
whenever I run my Rspec tests without an internet connection. So I'd like to stub that method so that it returns just a hash {:sessionId => 1}. But I'm having trouble figuring out how to stub the method. I can't just stub the OpenTok module or the OpenTok::OpenTokSDK class. How would I go about stubbing the create_session method?
here's what I've been doing that works:
First, what I tend to do is to initialize the OpenTok object when the app loads so I'm not creating an OpenTok object on every request. To do this, I create a ruby file (apis.rb) in my config/initializers folder.
My apis.rb looks like this:
TB_KEY = ENV['TB_KEY']
TB_SECRET = ENV['TB_SECRET']
OTSDK = OpenTok::OpenTokSDK.new TB_KEY, TB_SECRET
In my controller, to generate a session I'll simply call OTSDK.createSession, similar to what you already have.
To test with rspec, you can simply write in your test file:
OTSDK.stub(:createSession).and_return( {:sessionId => "1MX_2A3453095J0TJ30..."} )
If you run rspec with wifi turned off calling createSession should no longer throw an error.
Here's the documentation for rspec stubbing: http://rubydoc.info/gems/rspec-mocks/frames
Good Luck!
The trouble is, the create_session seems to throw an error whenever I run my Rspec tests without an internet connection.
Instead of attempting to stub, why not give your tests a mock internet connection with VCR?
After initial set up, VCR lets you run all of your tests as if you were actively connected to the internet. This allows you to run tests offline, speeds up all the tests that needed an active connection, and gives you a consistent set of results.
If you have a subscription to RailsCasts, Ryan made a video about VCR in episode 291

ipython redirect stdout display corruption

I'm developing a system in python, and one functionality I need is the ability to have console output go to both the console and a user-specified file. This is replicating the Diary function in MATLAB. I have the following that works perfectly well on both IDLE on windows and python cmdline in ubuntu (this all exists inside a module that gets loaded):
class diaryout(object):
def __init__(self):
self.terminal = sys.stdout
self.save = None
def __del__(self):
try:
self.save.flush()
self.save.close()
except:
# do nothing, just catch the error; maybe it self was instantiated, but never opened
1/1
self.save = None
def dclose(self):
self.__del__()
def write(self, message):
self.terminal.write(message)
self.save.write(message)
def dopen(self,outfile):
self.outfile = outfile
try:
self.save = open(self.outfile, "a")
except Exception, e:
# just pass out the error here so the Diary function can handle it
raise e
def Diary(outfile = None):# NEW TO TEST
global this_diary
if outfile == None:
# None passed, so close the diary file if one is open
if isinstance(this_diary, diaryout):
sys.stdout = this_diary.terminal # set the stdout back to stdout
this_diary.dclose() # flush and close the file
this_diary = None # "delete" it
else:
# file passed, so let's open it and set it for the output
this_diary = diaryout() # instantiate
try:
this_diary.dopen(outfile) # open & test that it opened
except IOError:
raise IOError("Can't open %s for append!"%outfile)
this_dairy=none # must uninstantiate it, since already did that
except TypeError:
raise TypeError("Invalid input detected - must be string filename or None: %s"%Diary.__doc__)
this_dairy=none # must uninbstantiate it, since already did that
sys.stdout = this_diary # set stdout to it
Far superior to both IDLE and the plain python cmline, I'm using ipython; herein my problem lies. I can turn on the "diary" perfectly fine with no error but the display on the console gets messed. The attached screenshot shows this . The output file also becomes similarly garbled. Everything goes back to normal when I undo the redirection with Diary(None). I have tried editing the code so that it never even writes to the file, with no effect. It seems almost like something is forcing an unsupported character set or something I don't understand.
Anyone have an idea about this?

How to disable Rack-Mini-Profiler temporarily?

I'm using rack mini profiler in rails just fine, but during some coding sessions especially where I'm working on a lot of different client side code, it gets in the way. (mainly in my client side debugging tools network graphs, etc.)
I'm trying to turn it off with a before filter, that also serves to see if the user is authorized to see the profile anyway, but "deauthorize" doesn't seem to do anything for me. Here's my code called as a before filter:
def miniprofiler
off = true
if off || !current_user
Rack::MiniProfiler.deauthorize_request
return
elsif current_user.role_symbols.include?(:view_page_profiles)
Rack::MiniProfiler.authorize_request
return
end
Rack::MiniProfiler.deauthorize_request
end
I also know there is a setting "Rack::MiniProfiler.config.authorization_mode" but I can't find docs on what the possible settings are, and not seeing it used in the code? Right now its telling me :allow_all, but :allow_none doesn't do anything either.
Even if I can just temporarily set a value in the dev environment file and restart the server, that would serve my purposes.
Get latest and type:
http://mysite.com?pp=disable
When you are done type
http://mysite.com?pp=enable
See ?pp=help for all the options:
Append the following to your query string:
pp=help : display this screen
pp=env : display the rack environment
pp=skip : skip mini profiler for this request
pp=no-backtrace : don't collect stack traces from all the SQL executed (sticky, use pp=normal-backtrace to enable)
pp=normal-backtrace (*) : collect stack traces from all the SQL executed and filter normally
pp=full-backtrace : enable full backtraces for SQL executed (use pp=normal-backtrace to disable)
pp=sample : sample stack traces and return a report isolating heavy usage (experimental works best with the stacktrace gem)
pp=disable : disable profiling for this session
pp=enable : enable profiling for this session (if previously disabled)
pp=profile-gc: perform gc profiling on this request, analyzes ObjectSpace generated by request (ruby 1.9.3 only)
pp=profile-gc-time: perform built-in gc profiling on this request (ruby 1.9.3 only)
You can also use Alt + p to toggle on Windows/Linux and Option + p on MacOS.
If you want the profiler to be disabled initially, and then activate on demand... add a pre-authorize callback in an initializer file like:
Rack::MiniProfiler.config.pre_authorize_cb = lambda {|env| ENV['RACK_MINI_PROFILER'] == 'on'}
then in your application controller, add a before_filter that looks for the pp param
before_filter :activate_profiler
def activate_profiler
ENV['RACK_MINI_PROFILER'] = 'on' if params['pp']
ENV['RACK_MINI_PROFILER'] = 'off' if params['pp'] == 'disabled'
end
your environment will not have RACK_MINI_PROFILER set initially, but if you want to turn it on, you can tack ?pp=enabled onto your url. Then you can disable again later (the pp=disabled will only turn it off for the current session, but setting the ENV variable to off will kill it entirely until you force it back on).

Resources