Require rest-client to module in Chef - ruby-on-rails-4

I need to include res-client into my module in order to use RestClient::Resource.
I use the method in the module in a Chef recipe (ruby_block resource).
When my ruby_block resource tries to run the method in the module it output this error:
ERROR: cannot load such file -- rest-client
The following is my module residing in libraries folder:
module SecretServer
def fetch_token
payload = { :username => "***", :password => "***", :grant_type => "****"}
uri = ***
request = RestClient::Resource.new(uri, :verify_ssl => false)
post_request = request.post payload, :content_type => 'application/x-www-form-urlencoded'
token = JSON.parse(post_request)["access_token"]
return token
end
end
require 'rest-client'
Chef::Recipe.include(SecretServer)
Chef::Resource.include(SecretServer)
The following is the resource that calls the function in module:
ruby_block 'parse data' do
block do
res = fetch_token
puts res
end
end
This is just one of the several recipes in my cookbook. This recipe runs after the target node is almost ready and 'bundle install' has been run on the target node.
I also install rest-client in the target node. I tried each of following resource before my ruby_block resource:
chef_gem 'rest-client' do
action :install
end
gem_package 'rest-client' do
action :install
end
My question is how to include 'rest-client' and utilize it in Chef recipes?

Long ago, the HTTP clients lived together in harmony. Then everything changed when the JSON gem attacked. Only the Chef::HTTP was still to be included with Chef as all the other clients were under too much flux to include.
We don't include that gem anymore, so to use it, you would have to install it yourself either via a cookbook gem dependency or a chef_gem resource. But for simple stuff you can just use our Chef::HTTP::SimpleJSON client instead:
Chef::HTTP::SimpleJson.new(uri).post("", args)["access_token"]
Or something like that (specifics depend on if you must use form encoding or if the server also speaks JSON).

Related

PG::ConnectionBad: connection is closed after upgrading rails from 4.2 to 5.2

I have upgraded my rails version of a project from 4.2 to 5.2.1 some of my tests are failed because of pg connection closed error on the full trace is is as following.
Failure/Error: DatabaseCleaner[:active_record].clean_with(:truncation)
ActiveRecord::StatementInvalid:
PG::ConnectionBad: connection is closed: TRUNCATE TABLE "public"."alerts", "public"."article_attachments", "public"."article_check_specification_tolerances", "public"."article_machine_part_settings", "public"."articles", "public"."attachments", "public"."check_batches", "public"."check_groups", "public"."check_specification_machine_types", "public"."check_specification_priorities", "public"."check_specification_responsibility_areas", "public"."check_specifications", "public"."checks", "public"."comments", "public"."counters", "public"."customers", "public"."defect_groups", "public"."defect_translations", "public"."defects", "public"."delayed_jobs", "public"."furnaces", "public"."gv_area_equipments", "public"."gv_areas", "public"."gv_components", "public"."gv_entries", "public"."gv_equipment_families", "public"."gv_equipments", "public"."gv_squads", "public"."gv_stop_reasons", "public"."gv_sub_equipment_components", "public"."gv_sub_equipments", "public"."job_specifications", "public"."jobs", "public"."lab_recipe_versions", "public"."lab_recipes", "public"."lines", "public"."machine_downtimes", "public"."machine_groups", "public"."machine_part_change_reasons", "public"."machine_part_changes", "public"."machine_part_translations", "public"."machine_parts", "public"."machine_type_group_machine_types", "public"."machine_type_groups", "public"."machine_types", "public"."messages", "public"."mold_sets", "public"."packing_schemes", "public"."rails_admin_settings", "public"."reasons", "public"."rejects", "public"."responsibility_areas", "public"."roles", "public"."settings", "public"."shift_definitions", "public"."shifts", "public"."system_log_entries", "public"."task_status_changes", "public"."tasks", "public"."tresholds", "public"."user_responsibility_areas", "public"."users", "public"."users_roles", "public"."workstations", "public"."machines", "public"."systematic_rejects", "public"."systematic_reject_machines" RESTART IDENTITY CASCADE;
and my rspec configurations are
RSpec.configure do |config|
config.around(:each) do |example|
DatabaseCleaner[:active_record].clean_with(:truncation)
# DatabaseCleaner.clean_with(:truncation)
DatabaseCleaner.cleaning do
example.run
end
end
end
strange thing is I can run tests one by one directory like
rspec spec/controllers/
rspec spec/contexts/
rspec spec/models
but it does not work when I try to run all in one with just
rspec spec/featues/
my feature_helper.rb is
require 'spec_helper'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'capybara/rails'
require 'rack/handler/puma'
require 'support/shared_activerecord_connection'
require 'support/feature_macros'
Capybara.register_server :puma do |app, port, host|
require 'rack/handler/puma'
Capybara.asset_host = "http://#{host}:#{port}"
Rack::Handler::Puma.run(app, Host: host, Port: port, Threads: '0:4', Silent: true, config_files: ['-'])
end
Capybara.configure do |config|
config.server = :puma
end
RSpec.configure do |config|
config.before(:suite) do
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
end
end
require 'spec_helper'
require 'counter_column_fix'
RedisStore.class_eval do
def self.new_instance
$redis = Redis.new(Rails.configuration.redis_config)
end
end
what should I do to remove this error?
DatabaseCleaner isn’t generally needed with Rails 5.1+ . Remove all references to it from your project and enable transactional testing in your RSpec config

Chefspec unit-testing

I'm no developer and a newbie with Chef.
I created a simple recipe and tested it on a test Kitchen and it works well but when I upload it to Jenkins it won't pass.
Can you help me point out what I'm missing?
Recipe:
# Recipe:: default
# Download VerneMQ
remote_file "#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb" do
source 'https://bintray.com/artifact/download/erlio/vernemq/deb/trusty/vernemq_1.4.0-1_amd64.deb'
end
# Install
dpkg_package 'vernemq_1.4.0-1_amd64.deb' do
source "#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb"
action :install
end
# Service Start
service 'vernemq' do
action [:enable, :start]
end
# Configurations
template '/etc/vernemq/vernemq.conf' do
source 'vernemq.conf.erb'
owner 'root'
group 'root'
mode '0644'
end
template '/etc/vernemq/vmq.passwd' do
source 'vmq.passwd.erb'
end
This is my unit test.
Unit Test:
require 'spec_helper'
require 'chefspec'
describe 'vernemq::default' do
let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '14.04').converge(described_recipe) }
it 'downloads the remote_file' do
expect(chef_run).to create_remote_file('#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb')
end
it 'installs a dpkg_package' do
expect(chef_run).to install_dpkg_package('vernemq')
end
it 'executes both actions' do
expect(chef_run).to enable_service('vernemq')
expect(chef_run).to start_service('vernemq')
end
it 'creates a file' do
expect(chef_run).to create_directory('/etc/vernemq/vernemq.conf')
end
it 'creates a file' do
expect(chef_run).to create_directory('/etc/vernemq/vmq.passwd')
end
end
errors from Jenkins
01:06:57 tm_vernemq::default
01:06:58 [2018-07-19T01:06:58-07:00] WARN: Chef::Provider::AptRepository already exists! Cannot create deprecation class for LWRP provider apt_repository from cookbook apt
01:06:58 [2018-07-19T01:06:58-07:00] WARN: Property sensitive of resource apt_repository overwrites an existing method. Please use a different property name. This will raise an exception in Chef 13. (CHEF-11)/tmp/d20180719-10648-933ma2/cookbooks/apt/resources/repository.rb:54:in class_from_file'.
01:06:58 Please see https://docs.chef.io/deprecations_property_name_collision.html for further details and information on how to correct this problem. at /opt/chefdk/embedded/lib/ruby/gems/2.3.0/gems/chef-12.19.36/lib/chef/event_dispatch/dispatcher.rb:43:incall'
01:06:58 [2018-07-19T01:06:58-07:00] WARN: AptRepository already exists! Deprecation class overwrites Custom resource apt_repository from cookbook apt
01:06:58 executes both actions
01:06:58 installs a dpkg_package (FAILED - 1)
01:06:58 creates a file (FAILED - 2)
01:06:58 creates a file (FAILED - 3)
01:06:58 downloads the remote_file (FAILED - 4)
01:06:58
01:06:58 Failures:
01:06:58
01:06:58 1) vernemq::default installs a dpkg_package
01:06:58 Failure/Error: expect(chef_run).to install_dpkg_package('vernemq')
01:06:58
01:06:58 expected "dpkg_package[vernemq]" with action :install to be in Chef run. Other dpkg_package resources:
01:06:58
01:06:58 dpkg_package[vernemq_1.4.0-1_amd64.deb]
01:06:58
01:06:58 # ./test/unit/recipes/default_spec.rb:18:in `block (2 levels) in <top (required)>'
01:06:58
01:06:58 2) tm_vernemq::default creates a file
01:06:58 Failure/Error: expect(chef_run).to create_directory('/etc/vernemq/vmq.passwd')
01:06:58
01:06:58 expected "directory[/etc/vernemq/vmq.passwd]" with action :create to be in Chef run. Other directory resources:
01:06:58
You didn't include the full error message so this is mostly a guess but you have dpkg_package 'vernemq_1.4.0-1_amd64.deb' do vs install_dpkg_package('vernemq'). Those need to have the same name in them.

Capybara::Poltergeist Status error, failed to reach server

I am trying to make some tests with Rspec/Capybara/Poltergeist on my Rails 4 application, Phantomjs is installed (version 2.2.1), but I always get this error :
Failure/Error: visit(perfect_landing_page_path)
Capybara::Poltergeist::StatusFailError:
Request to 'http://127.0.0.1:49623/path' failed to reach server, check DNS
and/or server status
The test i'm working on :
require 'rails_helper'
RSpec.feature 'Subscription', :type => :feature do
let!(:plan) { create(:plan) }
let!(:landing_page) { create(:landing_page) }
before(:each) { landing_page.default_plan = plan }
describe 'landing_page#perfect_show' do
scenario 'form display', js: true do
plan_2 = create(:plan)
plan_3 = create(:plan)
landing_page.plans << plan_2
landing_page.plans << plan_3
visit(perfect_landing_page_path)
expect(page).to have_css(".start-now", count: 3)
first(".start-now").click
expect(page).to have_css("#new_user")
end
end
end
My Gemfile looks like this :
gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
gem 'guard-rspec'
group :test do
gem 'database_cleaner'
gem 'capybara'
gem 'capybara-screenshot'
gem 'poltergeist'
gem 'selenium-webdriver'
gem 'shoulda-matchers', require: false
gem 'show_me_the_cookies'
end
My spec/support/capybara.rb file :
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require "capybara/poltergeist" # Add this line to require poltergeist
require 'selenium-webdriver'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {:js_errors => false, :default_max_wait_time => 30, :timeout => 30, phantomjs_options: [
'--load-images=no',
'--ignore-ssl-errors=true',
'--ssl-protocol=any']})
end
Capybara.register_driver :poltergeist_debug do |app|
Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.configure do |config|
config.javascript_driver = :poltergeist
config.ignore_hidden_elements = true
config.default_max_wait_time = 30
end
My spec_helper.rb file :
require 'capybara/rspec'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
Did someone encounter this problem before ? Does anyone have a solution for this ? I have been banging my head for days looking on the web...
Thank you very much.
PS : it works fine on my friend's mac (Yosemite or El Capitan), just not on mine.
I was having this problem in CI (CodeShip).
Adding a call to bundle exec rake assets:precompile at the end of the setup commands seemed to fix it:
CodeShip CI Setup Commands:
rvm use 2.3.4 --install
bundle install
export RAILS_ENV=test
bundle exec rake db:schema:load
bundle exec rake assets:precompile
Also had a whitelist per #agbodike but in the rails_helper.rb
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
I had the same issue and it was due to a 3rd party script timing out. You can prevent loading of 3rd party scripts with a blacklist. For example:
config.before(:each, js: true) do
page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end
would prevent any URL starting with http://use.typekit.net from being called for each test that uses the js driver. More information can be found at:
https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls
Alternatively you can use a whitelist:
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
which will block all requests not to 127.0.0.1
I placed the configuration in spec/feature_helper.rb to ensure it was only set for feature specs.
You can avoid these by precompile the assets before tests.
And the code is:
RSpec.configure do |config|
config.before :all do
ENV['PRECOMPILE_ASSETS'] ||= begin
case self.class.metadata[:type]
when :feature, :view
STDOUT.write "Precompiling assets..."
require 'rake'
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
STDOUT.puts " done."
Time.now.to_s
end
end
end
end
more info

Capistrano 3.4 Deployment Problems

I have inherited a Rails project and I am unable to deploy it using the supplied instructions using Capistrano. I am not familiar with capistrano at all.
Whatever I try I always get the following error message
(Backtrace restricted to imported tasks)
cap aborted!
ArgumentError: wrong number of arguments (1 for 2)
Tasks: TOP => production
(See full trace by running task with --trace)
This includes
$ bundle exec cap -T
$ bundle exec cap production deploy
I am following the guide here https://github.com/capistrano/capistrano
I have starred out important info but here is the a copy of the config/deploy/staging.rb
role :app, %w{deploy#**.**.**.**:****}
role :web, %w{deploy#**.**.**.**:****}
role :db, %w{deploy#**.**.**.**:****}
set :branch, 'develop'
set :deploy_to, '/var/www/soreen.staged.ws'
set :ssh_options, {
keepalive: true,
keepalive_interval: 60 #seconds
}
and here is Capfile
# Load DSL and Setup Up Stages
require 'capistrano/setup'
# Includes default deployment tasks
require 'capistrano/deploy'
require 'capistrano/rbenv'
require 'capistrano/bundler'
require 'capistrano/rails/migrations'
require 'capistrano/rails/assets'
require 'capistrano/rails/collection'
# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
and here is config/deploy.rb
# config valid only for current version of Capistrano
lock '3.4.0'
set :application, 'Soreen'
set :repo_url => "****************"
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')
set :rbenv_type, :user # or :system, depends on your rbenv setup
set :rbenv_ruby, '2.1.2'
set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=# {fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"
set :rbenv_map_bins, %w{rake gem bundle ruby rails}
set :rbenv_roles, :all # default value
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Your restart mechanism here, for example:
execute :mkdir, '-p', "#{ release_path }/tmp"
execute :touch, release_path.join('tmp/restart.txt')
end
end
after :publishing, :restart
after :restart, :clear_cache do
on roles(:web), in: :groups, limit: 3, wait: 10 do
end
end
end
Please help !
You can get a backtrace for the error using the following:
bundle exec cap --backtrace -T
That will give you more information. Likely this is a syntax error in your configuration.

Rails 4 I18n - missing translation after adding new locale file

Currently I have some locales subdirectories , which are correctly set in the configuration
config/application.rb
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
I have already 2 locales files , and I can get easily the translations :
config/locales/admin/dashboard.en.yml
en:
dashboard:
title: Dashboard
config/locales/admin/dashboard.fr.yml
fr:
dashboard:
title: Tableau de bord
irb(main):014:0> I18n.locale = :en
=> :en
irb(main):015:0> I18n.t("dashboard.title")
=> "Dashboard"
irb(main):016:0> I18n.locale = :fr
=> :fr
irb(main):017:0> I18n.t("dashboard.title")
=> "Tableau de bord"
Now I added 2 other locales files ( quite similar to previous ones...) into the SAME subdirectory 'locales/admin'
# =============
config/locales/admin/sheet.en.yml
en:
sheet:
title: Sheet
config/locales/admin/sheet.fr.yml
fr:
sheet:
title: Table
I RESTARTED the server ... and tried wo success to get the new added translations
irb(main):010:0> I18n.locale = :en
=> :en
irb(main):011:0> I18n.t("sheet.title")
=> "translation missing: en.sheet.title"
irb(main):012:0> I18n.locale = :fr
=> :fr
irb(main):013:0> I18n.t("sheet.title")
=> "translation missing: fr.sheet.title"
translations missing in BOTH languages? so I guess something is wrong in the subdirectories definition in the application.rb config file, as I checked the Rails.application.config.i18n.load_path ,a dn the newly added files ARE NOT in the path ..
"..../config/locales/admin/dashboard.en.yml",
"..../config/locales/admin/dashboard.fr.yml",
but not
"..../config/locales/admin/sheet.en.yml",
"..../config/locales/admin/sheet.fr.yml",
thanks for suggestions
It seems this issue has been already detected and it's related to the 'spring' process..
# https://github.com/rails/spring/issues/408
# rafaelfranca May 28
I think you got this error because you added the locale file after you
started the spring process for your environment, so when you add the
file it is not loaded inside the spring process. When you change the
application.rb the spring process is reloaded and your locale is now
working.
I changed one line ( added one blank line ...) in the application.rb than I restarted the server , and the new translations are found
rafael stated the rails console should restart the spring
Any rails command starts springs. rails console, rails generate,
rails server. You can stop the spring process with spring stop.
so, after ADDING a new locale file, better stopping spring before restarting the server
spring stop
rails server ( or rails console )
Change application.rb => Restart the Rails server
I would like to add that any time you make any change to application.rb you must restart the server for the change to take effect, not just the i18n component.