undefined method define_enum_for for RSpec::ExampleGroups - ruby-on-rails-4

I am getting undefined define_enum_for method error after upgrading rails to 4.2.0 from 4.1.
Is there any fix for this?
Rails : 4.2.0
Ruby : ruby 2.1.5p273 (2014-11-13 revision 48405) [i686-linux]
1) Recording
Failure/Error:
should define_enum_for(:state).
with({
initial: 'initial',
running: 'running',
stopped: 'stopped'
})
NoMethodError:
undefined method `define_enum_for' for #<RSpec::ExampleGroups::Recording:0x99a0ea8>
shoulda-matchers#define_enum_for

specifying the test_framework :rspec for shoulda-matchers#configuration solved this problem.
shoulda-matchers#configuration
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :active_record
with.library :active_model
with.library :action_controller
end
end

Configuration Required
spec_helper.rb/rails_helper.rb configure block
type: metadata
spec_helper.rb/rails_helper.rb
I required the Shoulda::Matchers configuration in the spec_helper.rb (the application had not been migrated to rails_helper.rb - but rails_helper.rb is the place I would have put it if available):
# spec/spec_helper.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails # same as :active_record + :active_model + :active_controller
end
end
Metadata
But, it also required the type: metadata before it worked:
This==============\/
describe User, type: :model do
it { should define_enum_for(:status) }
end

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

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

Error (upload image) after deploy using capistrano rails 4

Yesterday i tried to deploy my rails app to my own server. For deploy, i have followed gorails tutorial -> https://gorails.com/deploy/ubuntu/14.04. After deployed, finally my rails app has running live. But i have a problem when i try to create room module with image, i get error like this
We're sorry, but something went wrong.
If i create room without image, it success. I'm sure that i can't upload image.
gem 'paperclip'
room.rb
has_attached_file :image, :styles => { :for_index => "336x227>", :thumb => "150x150>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
deploy.rb
lock '3.1.0'
set :application, 'hotelxxxxx'
set :repo_url, 'git#bitbucket.org:xxxxxx/hotelxxxxx.git'
set :deploy_to, '/home/xxxxxx/hotelxxxxx'
set :linked_files, %w{config/database.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
execute :touch, release_path.join('tmp/restart.txt')
end
end
after :publishing, 'deploy:restart'
after :finishing, 'deploy:cleanup'
end
How to fix that?
The first step to troubleshoot this issue would be to look at the Rails log on your server. It should be in the log/production.log file. Having the actual error message in the log would make it a lot easier to help you figure this out.
Finally image uploaded !! I see error from nginx error.log => 'Paperclip::Errors::NotIdentifiedByImageMagick'. After that i try to re-install imagemagick from https://www.enovate.co.uk/web-design-blog/2015/02/25/how-to-install-imagemagick-from-source-on-ubuntu-14.04/
Imagemagick re-install succeed and open config/application.rb in my rails app
config/application.rb
# add line
Paperclip.options[:command_path] = "/usr/local/bin/identify"
Deploy again

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.2 console issues - using RAILS_ENV=development

trying to run
$ rails c RAILS_ENV=development
1 warning and 1 error are raised which I do not understand
# warning :
config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:
* development - set it to false
* test - set it to false (unless you use a tool that preloads your test environment)
* production - set it to true
# error
/config/initializers/devise.rb:13:in `+': no implicit conversion of nil into String (TypeError)
However , the config.eager_load is set to false in the development environment
config/environment/development.rb
Rails.application.configure do
config.cache_classes = false
config.eager_load = false
…/…
And looking at the config/initializers/devise.rb ( line 13) I have
config/initializers/devise.rb
Devise.setup do |config|
…/…
(13) config.mailer_sender = 'no-reply#' + Rails.application.secrets.domain_name
…/…
which lead to the config/secrets.yml file
config/secrets.yml
development:
domain_name: example.com
it's quite understandable , as running rails c ( whithout RAILS_ENV) , I get
$ rails c
development environment (Rails 4.2.3)
irb: warn: can't alias context from irb_context.
irb(main):001:0> Rails.application.secrets.domain_name
=> "example.com"
this warning is also cryptic :
irb: warn: can't alias context from irb_context
could not find any info on Google search... but at least it runs in development ....
why this warning and error using RAILS_ENV ? any enlightenment welcome
too bad .. I should HAVE READ the latest 4.2 doc !!!
so I should NOT be using RAILS_ENV at all !!
$ rails console staging
Loading staging environment (Rails 4.2.3)
irb(main):001:0> exit
$ rails console development
Loading development environment (Rails 4.2.3)
irb: warn: can't alias context from irb_context.
irb(main):001:0> exit